Home > Back-end >  Generating 2D grid indices using list comprehension
Generating 2D grid indices using list comprehension

Time:04-13

I would like to store the row and column indices of a 3 x 3 list in list. It should look like the following:

rc = [(0,0),(0,1),(0,2),(1,0),(1,1),(1,2),(2,0),(2,1),(2,2)]

How can I get this list using a list comprehension in Python?

CodePudding user response:

Some consider multiple for loops inside a list comprehension to be poor style. Use itertools.product() instead:

from itertools import product

list(product(range(3), repeat=2))

This outputs:

[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

CodePudding user response:

How about:

 [(x, y) for x in range(3) for y in range(3)]

CodePudding user response:

If I understand correctly, and the input is A, the B can be output as follows:

A = [[1,2,3],[4,5,6],[7,8,9]]
B =[(A[i], A[j]) for i in range(3) for j in range(3)]
  • Related