在for循环中使用python next()而不推进for循环
我想在for循环中使用next()来处理以下单词,而不推进for循环在for循环中使用python next()而不推进for循环,python,next,Python,Next,我想在for循环中使用next()来处理以下单词,而不推进for循环 words = ["please", "do", "loop", "in", "order"] for word in words: print word checknextword = str(next((word for word in words), None)) 因此,我想打印: >>>please >>>do >>>loop >>&g
words = ["please", "do", "loop", "in", "order"]
for word in words:
print word
checknextword = str(next((word for word in words), None))
因此,我想打印:
>>>please
>>>do
>>>loop
>>>in
>>>order
但代码产生了:
>>>please
>>>loop
>>>order
您可以这样做:
words = ["please", "do", "loop", "in", "order"]
for i,j in map(None, words, words[1:]): #j will contain the next word and None if i is the last element of the list
print i
[OUTPUT]
please
do
loop
in
order
您可以使用以下命令创建当前单词和下一个单词:
for word, next_word in zip(words[:-1], words[1:]):
print word
checknextword = next_word
您的问题不是很清楚——为什么要访问下一个项目,以及如何处理它 如果您只想访问下一个项目,文档中有一个不错的选项: 这使您可以一次迭代列表中的项目和以下项目(尽管列表末尾会有问题,但仍然不清楚您想要的是什么): 这就像“我想用我的枪开火而不开枪”
next()。如果您在生成器上调用它,它将进一步(对于给定的生成器)或引发StopIteration
看起来,您希望从next
获取当前项目旁边的项目。如果您在循环中使用相同的迭代器调用它,它将检索它,但会更进一步。sshashank124的答案提供了可能的解决方案
另一个解决方案是跟踪列表中的当前索引,并尝试获取一个项目,这是一个进一步的索引。不清楚您在这里要实现什么。您的示例输出将由word的简单形式生成:print(word)
。无法重现该问题。可能您需要类似的内容,无需指定words[:-1]
zip
将把输出截断为最短的argent长度(在本例中为第二个)。@jornsharpe:true。不过,我觉得它更明确。
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return izip(a, b)
words = ["please", "do", "loop", "in", "order"]
for word, nextword in pairwise(words):
### do something with word
### do something else based on next word