Skip to content

Instantly share code, notes, and snippets.

@pokk
Last active April 5, 2017 02:12
Show Gist options
  • Save pokk/da91f540e9ea4664fdead99b778ed031 to your computer and use it in GitHub Desktop.
Save pokk/da91f540e9ea4664fdead99b778ed031 to your computer and use it in GitHub Desktop.
Eazy way to run once for each cell in a map

Introduction

We use itertools.product lib to run a map instead of double for loop.

Detail

This functions is actually creating a Cartesian product.

Talk is cheap. Show me the code.

import itertools

size = 5
t_map = [[0 for _ in range(size)] for _ in range(size)]

# Run once for each cell.
for i, j in itertools.product(range(size), repeat=2):
    t_map[i][j] = 1


# For example
#
# for i, j in itertools.product(range(2), repeat=2):
#     print(i, j)
#
# output:
# 0, 0
# 0, 1
# 1, 0
# 1, 1
#
#
# for i, j in itertools.product(range(2), repeat=3):
#     print(i, j)
#
# output:
# 0, 0, 0
# 0, 0, 1
# 0, 1, 0
# 1, 0, 0
# 1, 0, 1
# 1, 1, 0
# 1, 1, 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment