简体   繁体   English

在Python中使用枚举迭代到len(list)-1

[英]Using enumerate in Python to iterate up to len(list) - 1

If I have a list 如果我有清单

A = [5, 2, 7, 4, 6, 1, 3, 2, 6, 19, 2, 6]

I can loop through all the elements but the last, using this code: 我可以使用以下代码遍历除最后一个元素之外的所有元素:

for i in range(len(A) - 1):
    pass

Can I use enumerate() in this loop to accomplish the same thing? 我可以在此循环中使用enumerate()完成同一件事吗?

Slice the list you provide to enumerate to achieve a similar effect: 切片你提供的名单enumerate ,以达到类似的效果:

for i, item in enumerate(A[:-1]):
    print(item, end=' ')

touches all, but the last, elements of the list A . 触及列表A所有(最后一个)元素。

Of course: 当然:

for i, item in enumerate(A[:-1]):
    pass

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

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