2

是否可以使用列表推导或数组推导来生成数组数组?

例如,我有一个从 0 到 9 的列表:

rng = range(0,10)

然后我想从上面的 rng 创建一个 5 对 cartesion 产品对。我尝试了以下但它不起作用。

[arr for (for i in range(0,5) arr[i] in rng)]   

它不编译。有人可以让我知道编码的正确方法吗?

4

3 回答 3

5

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.

于 2013-09-12T13:24:28.850 回答
4

你可以使用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()调用。

于 2013-09-12T13:20:59.257 回答
0

用列表理解来做这不是一个好方法,但如果你想这样做,你可以这样做:

[(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))
于 2013-09-12T13:28:32.650 回答