[英]Iterate over lists without two duplicates in a row
我想以類似於以下方式迭代整數列表:
itertools.product(range(n), repeat=5)
如果 n = 3 這給出:
[(0, 0, 0, 0, 0),
(0, 0, 0, 0, 1),
(0, 0, 0, 0, 2),
(0, 0, 0, 1, 0),
(0, 0, 0, 1, 1),
(0, 0, 0, 1, 2),
(0, 0, 0, 2, 0),
(0, 0, 0, 2, 1),
(0, 0, 0, 2, 2),
(0, 0, 1, 0, 0),
[...]
但是,我只想要那些連續兩次不具有相同數字的元組。 所以 (0,0,1,0,0) 會像許多其他人一樣被排除在外。
你怎么能做到這一點?
自己生成沒有連續重復的序列可能更有效,而不是使用itertools.product
生成所有序列並對其進行過濾。 我會使用這樣的遞歸生成器:
def gen(seq, n, prefix=()):
if n == 0:
yield prefix
return
for x in seq:
if not prefix or x != prefix[-1]:
yield from gen(seq, n-1, prefix+(x,))
示例輸出:
>>> list(gen(range(3), 5))
[(0, 1, 0, 1, 0),
(0, 1, 0, 1, 2),
(0, 1, 0, 2, 0),
(0, 1, 0, 2, 1),
(0, 1, 2, 0, 1),
(0, 1, 2, 0, 2),
(0, 1, 2, 1, 0),
(0, 1, 2, 1, 2),
(0, 2, 0, 1, 0),
(0, 2, 0, 1, 2),
(0, 2, 0, 2, 0),
(0, 2, 0, 2, 1),
(0, 2, 1, 0, 1),
(0, 2, 1, 0, 2),
(0, 2, 1, 2, 0),
(0, 2, 1, 2, 1),
(1, 0, 1, 0, 1),
(1, 0, 1, 0, 2),
(1, 0, 1, 2, 0),
(1, 0, 1, 2, 1),
(1, 0, 2, 0, 1),
(1, 0, 2, 0, 2),
(1, 0, 2, 1, 0),
(1, 0, 2, 1, 2),
(1, 2, 0, 1, 0),
(1, 2, 0, 1, 2),
(1, 2, 0, 2, 0),
(1, 2, 0, 2, 1),
(1, 2, 1, 0, 1),
(1, 2, 1, 0, 2),
(1, 2, 1, 2, 0),
(1, 2, 1, 2, 1),
(2, 0, 1, 0, 1),
(2, 0, 1, 0, 2),
(2, 0, 1, 2, 0),
(2, 0, 1, 2, 1),
(2, 0, 2, 0, 1),
(2, 0, 2, 0, 2),
(2, 0, 2, 1, 0),
(2, 0, 2, 1, 2),
(2, 1, 0, 1, 0),
(2, 1, 0, 1, 2),
(2, 1, 0, 2, 0),
(2, 1, 0, 2, 1),
(2, 1, 2, 0, 1),
(2, 1, 2, 0, 2),
(2, 1, 2, 1, 0),
(2, 1, 2, 1, 2)]
嘗試:
output = [
lst for lst in itertools.product(range(3), repeat=3)
if not any(i==j for i, j in zip(lst[:-1],lst[1:]))
]
您可以使用帶有警衛的綜合列表:
n = 3
repeat = 5
[l for l in itertools.product(range(n), repeat=repeat) if not any(l[n-1] == l[n] for n in range(1, repeat))]
這將過濾掉至少有一個與前一行相同的值的任何行。
如果您想使用更高級別的功能,您可以檢查 groupby 中的組數是否與重復相同。
n = 3
r = 5
out_gen = filter(
lambda x: len(tuple(itertools.groupby(x)))==r,
itertools.product(range(n), repeat=r)
)
這是對遞歸生成器方法的另一種看法,它基於從調用遞歸中排除值而不是傳遞整個結果:
def comb(A,n,x=None):
yield from ([v]+r for v in A if v!=x for r in comb(A,n-1,v)) if n else [[]]
輸出:
for p in comb(range(3),5):print(p)
[0, 1, 0, 1, 0]
[0, 1, 0, 1, 2]
[0, 1, 0, 2, 0]
[0, 1, 0, 2, 1]
[0, 1, 2, 0, 1]
[0, 1, 2, 0, 2]
[0, 1, 2, 1, 0]
[0, 1, 2, 1, 2]
[0, 2, 0, 1, 0]
[0, 2, 0, 1, 2]
[0, 2, 0, 2, 0]
[0, 2, 0, 2, 1]
[0, 2, 1, 0, 1]
[0, 2, 1, 0, 2]
[0, 2, 1, 2, 0]
[0, 2, 1, 2, 1]
[1, 0, 1, 0, 1]
[1, 0, 1, 0, 2]
[1, 0, 1, 2, 0]
[1, 0, 1, 2, 1]
[1, 0, 2, 0, 1]
[1, 0, 2, 0, 2]
[1, 0, 2, 1, 0]
[1, 0, 2, 1, 2]
[1, 2, 0, 1, 0]
[1, 2, 0, 1, 2]
[1, 2, 0, 2, 0]
[1, 2, 0, 2, 1]
[1, 2, 1, 0, 1]
[1, 2, 1, 0, 2]
[1, 2, 1, 2, 0]
[1, 2, 1, 2, 1]
[2, 0, 1, 0, 1]
[2, 0, 1, 0, 2]
[2, 0, 1, 2, 0]
[2, 0, 1, 2, 1]
[2, 0, 2, 0, 1]
[2, 0, 2, 0, 2]
[2, 0, 2, 1, 0]
[2, 0, 2, 1, 2]
[2, 1, 0, 1, 0]
[2, 1, 0, 1, 2]
[2, 1, 0, 2, 0]
[2, 1, 0, 2, 1]
[2, 1, 2, 0, 1]
[2, 1, 2, 0, 2]
[2, 1, 2, 1, 0]
[2, 1, 2, 1, 2]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.