Python:计算列表的笛卡尔功效的最短方法 [英] Python: shortest way to compute cartesian power of list
本文介绍了Python:计算列表的笛卡尔功效的最短方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我们有一个列表L
.笛卡尔积L x L
可以这样计算:
Suppose we have a list L
. The cartesian product L x L
could be computed like this:
product = [(a,b) for a in L for b in L]
如何以短而有效的方式计算笛卡尔乘方L x L x L x ... x L
(对于给定的n,n次)?
How can the cartesian power L x L x L x ... x L
(n times, for a given n) be computed, in a short and efficient way?
推荐答案
使用 itertools.product()
:
product = itertools.product(L, repeat=n)
其中product
现在是可迭代的;如果您想将其具体化为完整列表,请致电list(product)
:
where product
is now a iterable; call list(product)
if you want to materialize that to a full list:
>>> 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)]
这篇关于Python:计算列表的笛卡尔功效的最短方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文