Python: shortest way to compute cartesian power of list [duplicate]

时光总嘲笑我的痴心妄想 提交于 2020-02-03 08:50:59

问题


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]

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?


回答1:


Using itertools.product():

product = itertools.product(L, repeat=n)

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


来源:https://stackoverflow.com/questions/14615595/python-shortest-way-to-compute-cartesian-power-of-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!