[英]run through all combinations of a list with set numbers
我有一個項目需要在一個循環中遍歷一個列表的所有組合和一組數字。
例如
code = [4,3,2,1]
code = [4,3,1,2]
code = [4,2,1,3]
.
.
.
我試圖列出一長串數字來制作某種手冊
例如
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]
這可行,但如果我有大量代碼組合列表,則手冊會變得非常大。
有沒有更好的方法 - 還是我應該繼續使用手動版本?
我主要用 python 寫,但也可以讀很多其他語言,所以如果你想寫其他的,我也能理解
如果我正確理解您的問題, 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)
# ...
為此,您可以使用標准庫中提供的置換函數,如果您使用的是 Python 2.6 及更高版本,或者您使用的是 Python 3。
import itertools
permutations = list(itertools.permutations([1, 2, 3, 4]))
for i in list(perm):
print(i)
結果是:
(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.