Ori*_*eto 91 python loops list
这是很常见的,我遍历一个Python列表,让双方的内容和他们的索引.我通常做的是以下内容:
S = [1,30,20,30,2] # My list
for s, i in zip(S, range(len(S))):
# Do stuff with the content s and the index i
Run Code Online (Sandbox Code Playgroud)
我发现这个语法有点难看,尤其是zip函数内部.还有更优雅/ Pythonic的方法吗?
Ash*_*ary 168
用途enumerate():
>>> S = [1,30,20,30,2]
>>> for index, elem in enumerate(S):
print(index, elem)
(0, 1)
(1, 30)
(2, 20)
(3, 30)
(4, 2)
Run Code Online (Sandbox Code Playgroud)
Lev*_*von 21
像其他人一样:
for i, val in enumerate(data):
print i, val
Run Code Online (Sandbox Code Playgroud)
但也
for i, val in enumerate(data, 1):
print i, val
Run Code Online (Sandbox Code Playgroud)
换句话说,您可以指定enumerate()生成的索引/计数的起始值,如果您不希望索引以默认值零开始,则会派上用场.
我前几天在文件中打印出行,并将起始值指定为1 enumerate(),在向用户显示有关特定行的信息时,这比0更有意义.