有没有一种简单的方法可以在使用枚举循环时解开元组?


问题内容

考虑一下:

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

问题答案:

用这个:

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