对我来说,遍历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
我发现这个语法有点难看,特别是zip
函数中的部分。有没有更优雅的/Pythonic式的方法来做到这一点?
发布于 2012-07-14 01:55:35
使用enumerate
内置函数:http://docs.python.org/library/functions.html#enumerate
发布于 2012-07-14 01:56:04
>>> 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)
发布于 2012-07-14 01:56:23
enumerate
就是你想要的:
for i, s in enumerate(S):
print s, i
https://stackoverflow.com/questions/11475748
复制相似问题