简体   繁体   English

多个排列,包括重复

[英]Multiple permutations, including duplicates

I have a list of 6 elements L = ['a', 'b', 'c', 'd', 'e', 'f'] and would like to generate all possible 4 letter combinations - including duplicate values . 我有一个包含6个元素L = ['a', 'b', 'c', 'd', 'e', 'f']并希望生成所有可能的4个字母组合 - 包括重复值

ie ['a', 'b', 'c', 'd'] as well as ['a', 'a', 'a', 'a'] and ['a', 'a', 'b', 'b'] , etc. ['a', 'b', 'c', 'd']以及['a', 'a', 'a', 'a']['a', 'a', 'b', 'b']

So far I have been using import itertools: p = list(itertools.permutations(L, 4)) . 到目前为止,我一直在使用import itertools: p = list(itertools.permutations(L, 4)) (Python 2.7.6) (Python 2.7.6)

However, this is only giving me the 360 unique combinations, rather than the 1296 that I want. 然而,这只给了我360个独特的组合,而不是我想要的1296。

Thanks!! 谢谢!!

This is a cartesian product of 4 copies of the list. 这是4个副本列表的笛卡尔积。 You want itertools.product : 你想要itertools.product

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

One can solve this in at least 3 ways. 人们至少可以通过3种方式解决这个问题。

  1. Using nested loop 使用嵌套循环
  2. Using list comprehensions 使用列表推导
  3. Using itertools.product() 使用itertools.product()

Let's see how to use these and deep into the time performance of these: 让我们看看如何使用这些并深入了解这些的时间性能:

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))

Output: 输出:

1296
Nested Iterations took 0.001148 seconds
1296
List Comprehension took 0.000299 seconds
1296
itertools.product took 0.000227 seconds

So, comparing the ways we see that itertools.product() is simpler and effective than the others. 因此,比较我们看到itertools.product()比其他方法更简单有效的方式。

NB: The code is run in https://codepad.remoteinterview.io/ . 注意:代码在https://codepad.remoteinterview.io/中运行。 Performance may vary. 表现可能有所不同

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

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