Tuple unpacking in for loops

前端 未结 6 1384
感动是毒
感动是毒 2020-11-22 16:41

I stumbled across the following code:

for i,a in enumerate(attributes):
   labels.append(Label(root, text = a, justify = LEFT).grid(sticky = W))
   e = Entry         


        
6条回答
  •  迷失自我
    2020-11-22 17:04

    Take this code as an example:

    elements = ['a', 'b', 'c', 'd', 'e']
    index = 0
    
    for element in elements:
      print element, index
      index += 1
    

    You loop over the list and store an index variable as well. enumerate() does the same thing, but more concisely:

    elements = ['a', 'b', 'c', 'd', 'e']
    
    for index, element in enumerate(elements):
      print element, index
    

    The index, element notation is required because enumerate returns a tuple ((1, 'a'), (2, 'b'), ...) that is unpacked into two different variables.

提交回复
热议问题