简体   繁体   中英

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

If I understand your question correctly, itertools.permutations should do the trick:

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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