[英]How to make a list of the coordinates of all columns and rows
Suppose I have a nxn
grid, and I want a function that generates a list of all columns and rows by taking n
as the input, in python.假设我有一个
nxn
网格,并且我想要一个 function,它通过在 python 中以n
作为输入来生成所有列和行的列表。 By a list of columns, I mean each column is represented as its own list, with elements being coordinates of the elements in the column.通过列列表,我的意思是每列都表示为自己的列表,元素是列中元素的坐标。 (Or each column could be a set of coordinates, that would work too)
(或者每列可以是一组坐标,这也可以)
I could do this using two list comprehensions,我可以使用两个列表推导来做到这一点,
x = [[ (i, j) for j in range(n)] for i in range(n)] + [[ (i, j) for i in range(n)] for j in range(n)]
With n=3
this produces a list with 9 elements, each of which is a list of 3 coordinates.当
n=3
时,这会产生一个包含 9 个元素的列表,每个元素都是 3 个坐标的列表。
x = [[(0, 0), (0, 1), (0, 2)], [(1, 0), (1, 1), (1, 2)], [(2, 0), (2, 1), (2, 2)], [(0, 0), (1, 0), (2, 0)], [(0, 1), (1, 1), (2, 1)], [(0, 2), (1, 2), (2, 2)]]
I was wondering if there is a cleaner way to do the same thing, maybe using itertools or a similar module.我想知道是否有更清洁的方法来做同样的事情,也许使用 itertools 或类似的模块。
Not exactly sure if this is what you're looking for but you could try itertools.product
不完全确定这是否是您正在寻找的,但您可以尝试
itertools.product
For example例如
>>> from itertools import product
>>> n = 3
>>> list(product(range(n),range(n)))
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
>>> [list(product(range(n),range(n)))[n*i:n*i+n] for i in range(n)]
[[(0, 0), (0, 1), (0, 2)], [(1, 0), (1, 1), (1, 2)], [(2, 0), (2, 1), (2, 2)]]
>>> [list(product(range(n),range(n)))[i::n] for i in range(n)]
[[(0, 0), (1, 0), (2, 0)], [(0, 1), (1, 1), (2, 1)], [(0, 2), (1, 2), (2, 2)]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.