這不是排序像笛卡爾積;它是,正像一樣喜歡笛卡爾產品。
>>> from itertools import product
>>> list(product([0,1,5], repeat=2))
[(0, 0), (0, 1), (0, 5), (1, 0), (1, 1), (1, 5), (5, 0), (5, 1), (5, 5)]
>>> list(product([2,3], repeat=3))
[(2, 2, 2), (2, 2, 3), (2, 3, 2), (2, 3, 3), (3, 2, 2), (3, 2, 3), (3, 3, 2), (3, 3, 3)]
的填充工具爲itertools.product
如下:
def product(*args, **kwds):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
但既然你不能使用itertools,您不妨來寫一個稍微更有效的解決問題的方法的自由。因爲我們只是計算的n
相同iterables的產品,就讓我們把它叫做笛卡爾指數:
def cartesian_exponent(li, e=1):
pools = [li] * e
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
return result
或者遞歸使用另一個難以理解的列表理解:
def cartesian_exponent(li, e=1):
if e == 1:
return [[x] for x in li]
else:
return [[x]+y for x in li for y in cartesian_exponent(li, e=e-1)]
哪些可以被壓縮到一個線:
def cartesian_exponent(li, e=1):
return [[x] for x in li] if e == 1 else [[x] + y for x in li for y in cartesian_exponent(li, e=e-1)]
但是,那麼你會犧牲可讀性的簡潔,這是沒有bueno。不可理解的列表理解已經不夠透徹。
一些測試:
>>> cartesian_exponent([0,1,5], e=2)
[[0, 0], [0, 1], [0, 5], [1, 0], [1, 1], [1, 5], [5, 0], [5, 1], [5, 5]]
>>> cartesian_exponent([2,3], e=3)
[[2, 2, 2], [2, 2, 3], [2, 3, 2], [2, 3, 3], [3, 2, 2], [3, 2, 3], [3, 3, 2], [3, 3, 3]]
提示:不要使用'list'作爲名字,它是一個[內置函數(https://docs.python.org/3/library/ functions.html#FUNC列表)。 –
你有沒有考慮過使用[itertools.permutations](https://docs.python.org/2/library/itertools.html#itertools.permutations)? –
[如何在Python中生成列表的所有排列]可能的重複(http://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python) –