1

假设我有一个列表理解

[x,y,z] for x in a for y in a for z in a

假设这是我对尺寸 3 的理解,我希望能够相应地修改它,所以对于 2,我将只有 x,y,对于 4,我将拥有像 a、b、c、d 等...

有没有办法做到这一点?

4

1 回答 1

6

是的,您可以使用以下product功能:

from itertools import product
a = [1,2,3]
print list(product(a))
# gives: [(1,), (2,), (3,)]
print list(product(a, a))
# gives: [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
print list(product(a, a, a))
# gives: [(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 1), (1, 2, 2), (1, 2, 3), (1, 3, 1), (1, 3, 2), (1, 3, 3), (2, 1, 1), (2, 1, 2), (2, 1, 3), (2, 2, 1), (2, 2, 2), (2, 2, 3), (2, 3, 1), (2, 3, 2), (2, 3, 3), (3, 1, 1), (3, 1, 2), (3, 1, 3), (3, 2, 1), (3, 2, 2), (3, 2, 3), (3, 3, 1), (3, 3, 2), (3, 3, 3)]

或更方便地使用repeat关键字:

product(a, repeat=3)
于 2012-10-25T22:46:28.147 回答