2024-10-01 13:33:37 发布
网友
我想在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 >>>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
你的问题不太清楚——你为什么要访问下一个项目,你想用它做什么。在
如果您只想访问下一项,itertools package的文档中有一个不错的recipe for pairwise iteration:
def pairwise(iterable): "s -> (s0,s1), (s1,s2), (s2, s3), ..." a, b = tee(iterable) next(b, None) return izip(a, b)
这样,您就可以在列表中迭代这些项和以下项(尽管在列表的末尾会遇到问题,但您并不清楚您希望在列表中显示什么):
您可以使用以下方式同时使用当前和下一个单词:
for word, next_word in zip(words[:-1], words[1:]): print word checknextword = next_word
你可以这样做:
你的问题不太清楚——你为什么要访问下一个项目,你想用它做什么。在
如果您只想访问下一项,itertools package的文档中有一个不错的recipe for pairwise iteration:
这样,您就可以在列表中迭代这些项和以下项(尽管在列表的末尾会遇到问题,但您并不清楚您希望在列表中显示什么):
^{pr2}$您可以使用以下方式同时使用当前和下一个单词:
相关问题 更多 >
编程相关推荐