如何访问for循环中的上一个/下一个元素? [英] How to access the previous/next element in a for loop?

查看:43
本文介绍了如何访问for循环中的上一个/下一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在使用 循环时访问 list(或 tuple 或其他可迭代的)的下一个或上一个元素for 循环?

Is there a way to access a list's (or tuple's, or other iterable's) next or previous element while looping through it with a for loop?

l = [1, 2, 3]
for item in l:
    if item == 2:
        get_previous(l, item)

推荐答案

表示为生成器函数:

def neighborhood(iterable):
    iterator = iter(iterable)
    prev_item = None
    current_item = next(iterator)  # throws StopIteration if empty.
    for next_item in iterator:
        yield (prev_item, current_item, next_item)
        prev_item = current_item
        current_item = next_item
    yield (prev_item, current_item, None)

用法:

for prev,item,next in neighborhood(l):
    print prev, item, next

这篇关于如何访问for循环中的上一个/下一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆