Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.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_Python 3.x_Combinations - Fatal编程技术网

Python 不重复地测试不同长度的组合

Python 不重复地测试不同长度的组合,python,python-3.x,combinations,Python,Python 3.x,Combinations,在python中,我通过使用multiple for循环测试了固定长度的组合,有无重复。例如,如果我想测试每个长度为2且允许重复的数字组合(最多5个),我会这样做: list1=[1,2,3,4,5] for a in list1: for b in list1: print(str(a)+','+str(b) ) 对于固定长度来说,这似乎足够简单,但对于测试所有不同的长度来说,它并不那么有效。当长度变化时,使用此策略,我必须创建5组不同的1、2、3、4和5个循环。这已

在python中,我通过使用multiple for循环测试了固定长度的组合,有无重复。例如,如果我想测试每个长度为2且允许重复的数字组合(最多5个),我会这样做:

list1=[1,2,3,4,5]
for a in list1:
    for b in list1:
        print(str(a)+','+str(b) )

对于固定长度来说,这似乎足够简单,但对于测试所有不同的长度来说,它并不那么有效。当长度变化时,使用此策略,我必须创建5组不同的1、2、3、4和5个循环。这已经是非常冗长和丑陋的,但随着列表大小的增大,它会以指数级的方式变得更糟。我正在寻找一种更雄辩、更简单的方法来测试python中的所有这些组合。

您可以在循环中调用
itertools.compositions

import itertools
list1 = [1, 2, 3, 4, 5]

for i in range(1, len(list1)):
     print(list(itertools.combinations(list1, i)))

[(1,), (2,), (3,), (4,), (5,)]
[(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]
[(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5), (2, 3, 4), (2, 3, 5), (2, 4, 5), (3, 4, 5)]
[(1, 2, 3, 4), (1, 2, 3, 5), (1, 2, 4, 5), (1, 3, 4, 5), (2, 3, 4, 5)]

如果您的代码> List1有重复,您可以考虑通过转换为<代码> SET>代码>来删除它们,并重复进程。

或(重复)
itertools.product
。如果不希望重复,而是希望结果的所有顺序,则可能重复或
itertools.permutations
。“指数”是指二次:)