考虑一下:
the_data = ['a','b','c']
Run Code Online (Sandbox Code Playgroud)
使用枚举此循环可以写为:
for index,item in enumerate(the_data):
# index = 1 , item = 'a'
Run Code Online (Sandbox Code Playgroud)
如果 the_data = { 'john':'football','mary':'snooker','dhruv':'hockey'}
循环中使用键值对进行循环:
for name,sport in the_data.iteritems():
#name -> john,sport-> football
Run Code Online (Sandbox Code Playgroud)
使用枚举时,数据成为循环中的元组,因此在循环声明后需要一个额外的赋值行:
#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
Run Code Online (Sandbox Code Playgroud)
Ash*_*ary 13
用这个:
for index, (name, sport) in enumerate(the_data.iteritems()):
pass
Run Code Online (Sandbox Code Playgroud)
这相当于:
>>> a, (b, c) = [1, (2, 3)]
>>> a, b, c
(1, 2, 3)
Run Code Online (Sandbox Code Playgroud)
这也常用于zip和enumerate组合:
for i, (a, b) in enumerate(zip(seq1, seq2)):
pass
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
742 次 |
| 最近记录: |