在for循环中使用python next()in for循环

时间:2014-05-13 13:16:43

标签: 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
>>>in
>>>order

但代码产生:

>>>please
>>>loop
>>>order

4 个答案:

答案 0 :(得分:4)

您可以使用以下词语同时拥有当前和下一个词:

for word, next_word in zip(words[:-1], words[1:]):
    print word
    checknextword = next_word

答案 1 :(得分:1)

你可以这样做:

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

答案 2 :(得分:0)

您的问题不是很明确 - 您为什么要访问下一个项目,以及您想要用它做什么。

如果您只想访问下一个项目,recipe for pairwise iteration的文档中有一个不错的itertools package

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

答案 3 :(得分:0)

就像“我想在不射击的情况下开枪”。

使用生成器调用

next()方法,并且应该更进一步,检索下一个项目。如果你在生成器上调用它,它将更进一步(对于给定的生成器)或者提升StopIteration

看起来,就像您希望next获取当前项目旁边的项目一样。如果你在循环中使用相同的迭代器调用它,它将会对它进行检索,但会更进一步。答案byy sshashank124为此提供了可能的解决方案。

另一个解决方案是跟踪列表中的当前索引并尝试获取一个项目,这是一个索引。

相关问题