Python 多重排列,包括重复排列
我有一个包含6个元素的列表Python 多重排列,包括重复排列,python,list,duplicates,permutation,Python,List,Duplicates,Permutation,我有一个包含6个元素的列表L=['a','b','c','d','e','f'],并希望生成所有可能的4个字母组合-包括重复值 i、 e['a',b',c',d']以及['a',a',a',a']和['a',a',b',b']等 到目前为止,我一直在使用importitertools:p=list(itertools.permutations(L,4))。(Python 2.7.6) 然而,这只是给了我360个独特的组合,而不是我想要的1296 谢谢 这是列表4份副本的笛卡尔乘积。你想要: 我们
L=['a','b','c','d','e','f']
,并希望生成所有可能的4个字母组合-包括重复值
i、 e['a',b',c',d']
以及['a',a',a',a']
和['a',a',b',b']
等
到目前为止,我一直在使用importitertools:p=list(itertools.permutations(L,4))
。(Python 2.7.6)
然而,这只是给了我360个独特的组合,而不是我想要的1296
谢谢 这是列表4份副本的笛卡尔乘积。你想要:
我们至少可以用三种方法来解决这个问题
from time import time
# Solution 1
time_start = time()
L = ['a', 'b', 'c', 'd', 'e', 'f']
ar = []
for a in L:
for b in L:
for c in L:
for d in L:
ar.append([a,b,c,d])
print(len(ar))
time_end = time()
print('Nested Iterations took %f seconds' %(time_end-time_start))
# Solution 2
time_start = time()
L = ['a', 'b', 'c', 'd', 'e', 'f']
ar = [[a,b,c,d] for a in L for b in L for c in L for d in L]
print(len(ar))
time_end = time()
print('List Comprehension took %f seconds' %(time_end-time_start))
# Solution 3
import itertools
time_start = time()
L = ['a', 'b', 'c', 'd', 'e', 'f']
ar = list(itertools.product(L, repeat = 4))
print(len(ar))
time_end = time()
print('itertools.product took %f seconds' %(time_end-time_start))
输出:
1296
Nested Iterations took 0.001148 seconds
1296
List Comprehension took 0.000299 seconds
1296
itertools.product took 0.000227 seconds
因此,比较我们看到的itertools.product()
比其他方法更简单、更有效
注意:代码是在中运行的。性能可能会有所不同。从数学上讲,您寻找的是排列,而不是组合。集合中的项目组合是不同元素的无序集合(无重复项)。
1296
Nested Iterations took 0.001148 seconds
1296
List Comprehension took 0.000299 seconds
1296
itertools.product took 0.000227 seconds