Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 多重排列,包括重复排列_Python_List_Duplicates_Permutation - Fatal编程技术网

Python 多重排列,包括重复排列

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份副本的笛卡尔乘积。你想要: 我们

我有一个包含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份副本的笛卡尔乘积。你想要:


我们至少可以用三种方法来解决这个问题

  • 使用嵌套循环
  • 使用
  • 使用
  • 让我们看看如何使用这些工具,并深入了解这些工具的时间性能:

    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