Tuple unpacking in for loops

前端 未结 6 1379
感动是毒
感动是毒 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:08

    Short answer, unpacking tuples from a list in a for loop works. enumerate() creates a tuple using the current index and the entire current item, such as (0, ('bob', 3))

    I created some test code to demonstrate this:

        list = [('bob', 3), ('alice', 0), ('john', 5), ('chris', 4), ('alex', 2)]
    
        print("Displaying Enumerated List")
        for name, num in enumerate(list):
            print("{0}: {1}".format(name, num))
    
        print("Display Normal Iteration though List")
        for name, num in list:
            print("{0}: {1}".format(name, num))
    

    The simplicity of Tuple unpacking is probably one of my favourite things about Python :D

提交回复
热议问题