Loop through list with both content and index

It is very common for me to loop through a python list to get both the contents and their indexes. What I usually do is the following:

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

I find this syntax a bit ugly, especially the part inside the zip function. Are there any more elegant/Pythonic ways of doing this?

157215 次浏览

使用 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)

enumerate是你想要的:

for i, s in enumerate(S):
print s, i
>>> for i, s in enumerate(S):

enumerate()让这个更漂亮:

for index, value in enumerate(S):
print index, value

有关更多信息,请参见 给你

和其他人一样:

for i, val in enumerate(data):
print i, val

但是 还有

for i, val in enumerate(data, 1):
print i, val

换句话说,您可以为由 枚举()生成的索引/计数指定为 起始值,如果您不希望您的索引以 默认值为零开始,这将非常方便。

前几天,我打印了一个文件中的行,并将 enumerate()的起始值指定为1,这在向用户显示特定行的信息时比0更有意义。