Python 列出iterable的每个排列
我得到以下信息:Python 列出iterable的每个排列,python,permutation,Python,Permutation,我得到以下信息: from itertools import permutations l = [0, 1, 2, 3, 4] x = permutations (l, 3) 这正是人们所期望的。 但我需要的是: (0, 1, 2) , (0, 1, 3), ...., (0, 2, 1), (0, 2, 3), (0,2,4),...., (4, 3, 0), (4, 3, 1), (4, 3, 2) 如何实现这一点?您需要的是一个置换,或者一个产品,但是itertool的置换产生置换而不
from itertools import permutations
l = [0, 1, 2, 3, 4]
x = permutations (l, 3)
这正是人们所期望的。
但我需要的是:
(0, 1, 2) , (0, 1, 3), ...., (0, 2, 1), (0, 2, 3), (0,2,4),...., (4, 3, 0), (4, 3, 1),
(4, 3, 2)
如何实现这一点?您需要的是一个置换,或者一个产品,但是
itertool
的置换
产生置换而不需要置换。您可以自己计算产品:
(0, 0, 0), (0, 0, 1), ...., (0, 0, 4), (0, 1, 0), (0, 1, 1)........
或者使用itertools
中的同名函数:
[(x,y,z) for x in l for y in l for z in l]
#[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 0, 4), (0, 1, 0), ...
后一种方法更有效。您需要的是一种置换,或者一种产品,但是
itertool
的置换
产生置换而不需要置换。您可以自己计算产品:
(0, 0, 0), (0, 0, 1), ...., (0, 0, 4), (0, 1, 0), (0, 1, 1)........
或者使用itertools
中的同名函数:
[(x,y,z) for x in l for y in l for z in l]
#[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 0, 4), (0, 1, 0), ...
后一种方法更有效。您需要使用
产品
,而不是使用排列
,从itertools
模块,如以下示例:
list(itertools.product(l,repeat=3))
# [(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 0, 4), (0, 1, 0),...
输出:
from itertools import product
l = [0, 1, 2, 3, 4]
# Or:
# b = list(product(l, repeat=3))
b = list(product(l,l,l))
print(b)
您需要使用
itertools
模块中的产品
,而不是使用排列
,如下示例:
list(itertools.product(l,repeat=3))
# [(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 0, 4), (0, 1, 0),...
输出:
from itertools import product
l = [0, 1, 2, 3, 4]
# Or:
# b = list(product(l, repeat=3))
b = list(product(l,l,l))
print(b)
你需要的是产品,而不是排列
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), ..., (4, 4, 1), (4, 4, 2), (4, 4, 3), (4, 4, 4)]
你需要的是产品,而不是排列
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), ..., (4, 4, 1), (4, 4, 2), (4, 4, 3), (4, 4, 4)]
你没有解释结果应该包含什么。但是,检查itertools中的其他函数,看看其中一个函数是否适合您的需要。您没有解释结果应该包含什么。但是,请检查itertools中的其他功能,看看是否有一个适合您的需要。