也访问上一个和下一个值的循环
问题描述:
如何遍历对象列表,访问上一个、当前和下一个项目?喜欢这个 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.