多个包含重复的排列
我有一个包含6个元素的列表 L = ['a', 'b', 'c', 'd', 'e', 'f']
,我想生成所有可能的4个字母组合——包括重复的值。
比如说 ['a', 'b', 'c', 'd']
这样的组合,还有 ['a', 'a', 'a', 'a']
和 ['a', 'a', 'b', 'b']
等等。
到目前为止,我一直在使用 import itertools: p = list(itertools.permutations(L, 4))
。 (Python 2.7.6)
但是,这样只给我提供了360种独特的组合,而不是我想要的1296种。
谢谢!!
2 个回答
2
这个问题可以用至少三种方法来解决。
- 使用嵌套循环
- 使用列表推导式
- 使用itertools.product()
接下来我们来看看如何使用这些方法,并深入了解它们的时间性能:
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()
比其他方法更简单有效。
注意:代码是在https://codepad.remoteinterview.io/上运行的。性能可能会有所不同。
11
这是一个列表的四个副本的笛卡尔积。你需要用到itertools.product
这个工具:
import itertools
itertools.product(L, repeat=4)