Skip to main content
 首页 » 编程设计

动态大小的Python列表理解

2025年05月04日17mayingbao

假设我有一个列表理解

[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)