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

后端 未结 11 665
执念已碎
执念已碎 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:36

    It's nice to have when you need to use the index for some kind of manipulation and having the current element doesn't suffice. Take for instance a binary tree that's stored in an array. If you have a method that asks you to return a list of tuples that contains each nodes direct children then you need the index.

    #0 -> 1,2 : 1 -> 3,4 : 2 -> 5,6 : 3 -> 7,8 ...
    nodes = [0,1,2,3,4,5,6,7,8,9,10]
    children = []
    for i in range(len(nodes)):
      leftNode = None
      rightNode = None
      if i*2 + 1 < len(nodes):
        leftNode = nodes[i*2 + 1]
      if i*2 + 2 < len(nodes):
        rightNode = nodes[i*2 + 2]
      children.append((leftNode,rightNode))
    return children
    

    Of course if the element you're working on is an object, you can just call a get children method. But yea, you only really need the index if you're doing some sort of manipulation.

提交回复
热议问题