![](/img/trans.png)
[英]How to generate increasing permutations of a list in Python without itertools.combinations
[英]How to generate permutations of a list without “moving” zeros. in Python
使用itertools
工具,我可以對給定的數字列表進行所有可能的排列,但是如果列表如下:
List=[0,0,0,0,3,6,0,0,5,0,0]
itertools
不“知道”迭代零是浪費的工作,例如,以下迭代將出現在結果中:
List=[0,3,0,0,0,6,0,0,5,0,0]
List=[0,3,0,0,0,6,0,0,5,0,0]
它們是相同的,但是itertools
僅取第一個零(例如),並將其移至列表的第四位,反之亦然。
問題是:我怎樣才能僅迭代某些選定的數字,而讓其他數字(如零)不予處理? 可以有或沒有itertools
。
Voilá-它現在可以工作-在獲得“肉”的排列后,我進一步獲得了“ 0”位置的所有可能組合,並為非0的每個排列對“ 0位置”的每個可能集合產生了一個排列:
from itertools import permutations, combinations
def permut_with_pivot(sequence, pivot=0):
pivot_indexes = set()
seq_len = 0
def yield_non_pivots():
nonlocal seq_len
for i, item in enumerate(sequence):
if item != pivot:
yield item
else:
pivot_indexes.add(i)
seq_len = i + 1
def fill_pivots(permutation):
for pivot_positions in combinations(range(seq_len), len(pivot_indexes)):
sequence = iter(permutation)
yield tuple ((pivot if i in pivot_positions else next(sequence)) for i in range(seq_len))
for permutation in permutations(yield_non_pivots()):
for filled_permutation in fill_pivots(permutation):
yield filled_permutation
(我使用了Python的3個“非本地”關鍵字-如果您仍在使用Python 2.7,則必須采取另一種方法,例如使seq_len
成為一個包含單個項目的列表,然后可以將其替換在內部函數上)
我的第二次嘗試 (實際上是第三次)
這是一種幼稚的方法,僅保留已“看到”的排列的緩存-它節省了對每個排列所做的工作,但沒有生成所有可能的排列的工作:
from itertools import permutations
def non_repeating_permutations(seq):
seen = set()
for permutation in permutations(seq):
hperm = hash(permutation)
if hperm in seen:
continue
seen.add(hperm)
yield permutation
將每個結果附加到列表。 現在,您將擁有每種可能的組合,然后執行以下操作:
list(set(your_big_list))
Set會將列表縮小到僅唯一排列。 我不能完全確定這是您要解決的問題還是擔心性能。 不管剛做一個帳戶,我都想貢獻一點
您的問題尚不清楚,但是如果您嘗試列出排列而輸出中沒有0
,則可以按以下方式進行操作:
from itertools import permutations
def perms( listy ):
return permutations( [i for i in listy if i!=0])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.