是否可以使用列表推导或数组推导来生成数组数组?
例如,我有一个从 0 到 9 的列表:
rng = range(0,10)
然后我想从上面的 rng 创建一个 5 对 cartesion 产品对。我尝试了以下但它不起作用。
[arr for (for i in range(0,5) arr[i] in rng)]
它不编译。有人可以让我知道编码的正确方法吗?
To do it with a list comprehension:
[ (x, y) for x in rangeA for y in rangeB ]
I would use itertools.product
, though, as it is more self-documenting.
After re-reading your question, it also appears you want to compute a cross-product of arbitrary dimension, something that can't be parameterized in a list comprehension.
你可以使用itertools.product()
:
In [4]: list(itertools.product(range(10), repeat=2))
Out[4]:
[(0, 0),
(0, 1),
(0, 2),
...
(9, 6),
(9, 7),
(9, 8),
(9, 9)]
根据需要调整repeat
参数(听起来像是在寻找repeat=5
)。
如果您只需要一个可迭代而不是列表,则可以省略list()
调用。
用列表理解来做这不是一个好方法,但如果你想这样做,你可以这样做:
[(i,j,k,l,m) for i in range(10) for j in range(10) for k in range(10) for l in range(10) for m in range(10)]
但我建议你itertools.product()
按照@NPE 的建议去做:
list(itertools.product(range(10), repeat=5))