繁体   English   中英

多个排列,包括重复

[英]Multiple permutations, including duplicates

我有一个包含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。

谢谢!!

这是4个副本列表的笛卡尔积。 你想要itertools.product

import itertools
itertools.product(L, repeat=4)

人们至少可以通过3种方式解决这个问题。

  1. 使用嵌套循环
  2. 使用列表推导
  3. 使用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/中运行。 表现可能有所不同

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM