简体   繁体   English

Python - 向后迭代列表中的范围

[英]Python - backwards iteration through range in list

I'd like to search backwards through a list我想通过列表向后搜索

This is code that I read in other posts should work这是我在其他帖子中阅读的代码应该可以工作

ls = [1, 2, 3]

for i in range(len(ls)-1, 0, -1):
    print(i)

The output would be: output 将是:

2
1

Wheras if I use this code:如果我使用此代码:

ls = [1, 2, 3]

for i in range(len(ls)-1, -1, -1):
    print(i)

The output is: output 是:

2
1
0

Why is it that range(len(ls)-1, 0, -1) skips an element, and why is it recommended as a solution for backwards iteration (rather than range(len(ls)-1, -1, -1) )?为什么range(len(ls)-1, 0, -1)会跳过一个元素,为什么建议将其作为向后迭代的解决方案(而不是range(len(ls)-1, -1, -1) )?

If you don't mind the index being negative, you can do:如果您不介意索引为负数,则可以执行以下操作:

a = [1,2,3]
for i in range(-1, -1*(len(a)+1), -1):
    print(i, a[i])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM