也访问上一个和下一个值的循环 [英] Loop that also accesses previous and next values

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

问题描述

如何遍历对象列表,访问上一个、当前和下一个项目?喜欢这个 C/C++ 代码,在 Python 中?

How can I iterate over a list of objects, accessing the previous, current, and next items? Like this C/C++ code, in Python?

foo = somevalue;
previous = next = 0;

for (i=1; i<objects.length(); i++) {
    if (objects[i]==foo) {
        previous = objects[i-1];
        next = objects[i+1];
    }
}

推荐答案

这应该可以解决问题.

foo = somevalue
previous = next_ = None
l = len(objects)
for index, obj in enumerate(objects):
    if obj == foo:
        if index > 0:
            previous = objects[index - 1]
        if index < (l - 1):
            next_ = objects[index + 1]

这是关于 enumerate 函数的文档.

Here's the docs on the enumerate function.

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

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