Tuple unpacking in for loops

前端 未结 6 1396
感动是毒
感动是毒 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 16:55

    You could google on "tuple unpacking". This can be used in various places in Python. The simplest is in assignment

    >>> x = (1,2)
    >>> a, b = x
    >>> a
    1
    >>> b
    2
    

    In a for loop it works similarly. If each element of the iterable is a tuple, then you can specify two variables and each element in the loop will be unpacked to the two.

    >>> x = [(1,2), (3,4), (5,6)]
    >>> for item in x:
    ...     print "A tuple", item
    A tuple (1, 2)
    A tuple (3, 4)
    A tuple (5, 6)
    >>> for a, b in x:
    ...     print "First", a, "then", b
    First 1 then 2
    First 3 then 4
    First 5 then 6
    

    The enumerate function creates an iterable of tuples, so it can be used this way.

提交回复
热议问题