简体   繁体   English

遍历具有集合编号的列表的所有组合

[英]run through all combinations of a list with set numbers

I have a project that needs to run through all combinations of a list with set numbers in a loop.我有一个项目需要在一个循环中遍历一个列表的所有组合和一组数字。

eg例如

code = [4,3,2,1]
code = [4,3,1,2]
code = [4,2,1,3]
.
.
.

I have tried to make a long list of numbers to make some sort of manual我试图列出一长串数字来制作某种手册

eg例如

code = [4,3,2,1]
manual = [1,2,1,2,1,3,1,2,1,2,1,3,1,2,1,2,1,3,1,2,1,2,1,0]
for m in manual:
    print(code)
    if m == 1:
        code[-1], code[-2] = code[-2], code[-1]
    elif m == 2:
        code[-1], code[-3] = code[-3], code[-1]
    elif m == 3:
        code[-1], code[-2] , code[-3] , code[-4] = code[-4], code[-3] , code[-2] , code[-1]

This works, but the manual gets very large if I have a large number of code combinations lists.这可行,但如果我有大量代码组合列表,则手册会变得非常大。

Is there a better way of doing it - or should I just keep going with the manual version?有没有更好的方法 - 还是我应该继续使用手动版本?

I mainly write in python but can also read many other languages, so if you want to write in another, I can understand that too我主要用 python 写,但也可以读很多其他语言,所以如果你想写其他的,我也能理解

If I understand your question correctly, itertools.permutations should do the trick:如果我正确理解您的问题, itertools.permutations应该可以解决问题:

from itertools import permutations

code = [4,3,2,1]
for perm in permutations(code):
    print(perm)
# (4, 3, 2, 1)
# (4, 3, 1, 2)
# (4, 2, 3, 1)
# ...

For this, you can use the permutations functions provided in the standard library, if you are using Python 2.6 and above, or you are using Python 3.为此,您可以使用标准库中提供的置换函数,如果您使用的是 Python 2.6 及更高版本,或者您使用的是 Python 3。

import itertools
permutations = list(itertools.permutations([1, 2, 3, 4]))

for i in list(perm):  
  print(i)

Which results in:结果是:

(1, 2, 3, 4)
(1, 2, 4, 3)
(1, 3, 2, 4)
(1, 3, 4, 2)
(1, 4, 2, 3)
(1, 4, 3, 2)
(2, 1, 3, 4)
(2, 1, 4, 3)
(2, 3, 1, 4)
(2, 3, 4, 1)
(2, 4, 1, 3)
(2, 4, 3, 1)
(3, 1, 2, 4)
(3, 1, 4, 2)
(3, 2, 1, 4)
(3, 2, 4, 1)
(3, 4, 1, 2)
(3, 4, 2, 1)
(4, 1, 2, 3)
(4, 1, 3, 2)
(4, 2, 1, 3)
(4, 2, 3, 1)
(4, 3, 1, 2)
(4, 3, 2, 1)

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

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