Is there a need for range(len(a))?

后端 未结 11 691
执念已碎
执念已碎 2020-12-02 05:05

One frequently finds expressions of this type in python questions on SO. Either for just accessing all items of the iterable

for i in range(len(a)):
    prin         


        
11条回答
  •  天命终不由人
    2020-12-02 05:41

    What if you need to access two elements of the list simultaneously?

    for i in range(len(a[0:-1])):
        something_new[i] = a[i] * a[i+1]
    

    You can use this, but it's probably less clear:

    for i, _ in enumerate(a[0:-1]):
         something_new[i] = a[i] * a[i+1]
    

    Personally I'm not 100% happy with either!

提交回复
热议问题