Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
假设我们有一个列表L。笛卡尔积L x L可以这样计算:
L
L x L
product = [(a,b) for a in L for b in L]
如何L x L x L x ... x L以一种简短有效的方式计算笛卡尔幂(n 次,对于给定的 n)?
L x L x L x ... x L
使用itertools.product():
itertools.product()
product = itertools.product(L, repeat=n)
现在哪里product是可迭代的;list(product)如果您想将其具体化为完整列表,请致电:
product
list(product)
>>> from itertools import product >>> list(product(range(3), repeat=2)) [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]