循环遍历包含内容和索引的列表 [英] Loop through list with both content and index
本文介绍了循环遍历包含内容和索引的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
循环遍历python列表以获取内容和它们的索引是很常见的.我通常做的事情如下:
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
我觉得这个语法有点难看,尤其是 zip
函数内部的部分.有没有更优雅/Pythonic 的方法来做到这一点?
I find this syntax a bit ugly, especially the part inside the zip
function. Are there any more elegant/Pythonic ways of doing this?
推荐答案
使用 enumerate
内置函数:http://docs.python.org/library/functions.html#enumerate
这篇关于循环遍历包含内容和索引的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文