﻿ 如何在不“移动”零的情况下生成列表的排列.在Python中 - 代码日志

#### 如何在不“移动”零的情况下生成列表的排列.在Python中

``````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]
``````

Voilá – 它现在有效 – 在获得“肉”的排列后,我进一步获得了所有可能的“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:
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,

``````from itertools import permutations

def non_repeating_permutations(seq):
seen = set()
for permutation in permutations(seq):
hperm = hash(permutation)
if hperm in seen:
continue