我一直在思考为什么这些脚本的输出是不一致的。有谁可以帮我这个?
import itertools
from itertools import tee
from itertools import islice
words = ['Salad','with','Chocolate','and','potatoes']
nwise = lambda xs,n=2: zip(*(islice(xs,idx,None) for idx,xs in enumerate(tee(xs,n))))
doubles = list(map(lambda x: " ".join(x), nwise(words,2)))
triples = list(map(lambda x: " ".join(x), nwise(words,3)))
quadrouples = list(map(lambda x: " ".join(x), nwise(words,4)))
words.extend(doubles)
words.extend(triples)
words.extend(quadrouples)
print(words)
结果是['Salad', 'with', 'Chocolate', 'and', 'potatoes', 'Salad with', 'with Chocolate', 'Chocolate and', 'and potatoes', 'Salad with Chocolate', 'with Chocolate and', 'Chocolate and potatoes', 'Salad with Chocolate and', 'with Chocolate and potatoes']
import itertools
from itertools import tee
from itertools import islice
words = ['Salad','with','Chocolate','and','potatoes']
nwise = lambda xs,n=2: zip(*(islice(xs,idx,None) for idx,xs in enumerate(tee(xs,n))))
for i in range(2,5):
new = list(map(lambda x: " ".join(x), nwise(words,i)))
words.extend(new)
print(words)
结果是['Salad', 'with', 'Chocolate', 'and', 'potatoes', 'Salad with', 'with Chocolate', 'Chocolate and', 'and potatoes', 'Salad with Chocolate', 'with Chocolate and', 'Chocolate and potatoes', 'and potatoes Salad with', 'potatoes Salad with with Chocolate', 'Salad with with Chocolate Chocolate and', 'with Chocolate Chocolate and and potatoes', 'Salad with Chocolate and', 'with Chocolate and potatoes', 'Chocolate and potatoes Salad with', 'and potatoes Salad with with Chocolate', 'potatoes Salad with with Chocolate Chocolate and', 'Salad with with Chocolate Chocolate and and potatoes', 'with Chocolate Chocolate and and potatoes Salad with Chocolate', 'Chocolate and and potatoes Salad with Chocolate with Chocolate and', 'and potatoes Salad with Chocolate with Chocolate and Chocolate and potatoes', 'Salad with Chocolate with Chocolate and Chocolate and potatoes and potatoes Salad with', 'with Chocolate and Chocolate and potatoes and potatoes Salad with potatoes Salad with with Chocolate', 'Chocolate and potatoes and potatoes Salad with potatoes Salad with with Chocolate Salad with with Chocolate Chocolate and', 'and potatoes Salad with potatoes Salad with with Chocolate Salad with with Chocolate Chocolate and with Chocolate Chocolate and and potatoes']
为什么带有range()函数的for循环会产生与逐行方法不一致的结果?
答案 0 :(得分:3)
循环修改它时,create a new collection通常更安全。
扩展到新列表,例如words_
:
...
words_ = []
for i in range(2, 5):
new = list(map(lambda x: " ".join(x), nwise(words,i)))
words_.extend(new)
print(words_)
或者,使用words
所需结果列表扩展现有new
列表。
替换:
...
for i in range(2,5):
new = list(map(lambda x: " ".join(x), nwise(words,i)))
words.extend(new)
...
带
...
new = [" ".join(x) for i in range(2, 5) for x in nwise(words,i)]
words.extend(new)
...