在使用枚举循环时,是否有一种简单的方法可以解包元组?

时间:2014-02-03 14:14:27

标签: python

考虑一下:

the_data = ['a','b','c']

使用枚举此循环可以写为:

  for index,item in enumerate(the_data):
     # index = 1 , item = 'a'

如果the_data = { 'john':'football','mary':'snooker','dhruv':'hockey'}

循环,在循环中分配键值对:

for name,sport in the_data.iteritems():
 #name -> john,sport-> football

使用枚举时,数据成为循环中的元组,因此在循环声明后需要一个额外的赋值行:

#can assignment of name & sport happen within the `for-in` line itself ?
 for index,name_sport_tuple in enumerate(the_data.iteritems()):
         name,sport = name_sport_tuple  # Can this line somehow be avoided ?
         #index-> 1,name-> john, sport -> football 

1 个答案:

答案 0 :(得分:13)

使用此:

for index, (name, sport) in enumerate(the_data.iteritems()):
   pass

这相当于:

>>> a, (b, c) = [1, (2, 3)]
>>> a, b, c
(1, 2, 3)

这通常与zipenumerate组合一起使用:

for i, (a, b) in enumerate(zip(seq1, seq2)):
    pass
相关问题