假设我有一个列表理解
[x,y,z] for x in a for y in a for z in a
假设这是我对尺寸 3 的理解,我希望能够相应地修改它,所以对于 2,我将只有 x,y,对于 4,我将拥有像 a、b、c、d 等...
有没有办法做到这一点?
是的,您可以使用以下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)