简体   繁体   English

使用 Python 中的索引迭代列表

[英]Iterate a list with indexes in Python

I could swear I've seen the function (or method) that takes a list, like this [3, 7, 19] and makes it into iterable list of tuples, like so: [(0,3), (1,7), (2,19)] to use it instead of:我可以发誓我已经看到了 function (或方法),它需要一个列表,像这样[3, 7, 19]并使其成为可迭代的元组列表,如下所示: [(0,3), (1,7), (2,19)]来代替:

for i in range(len(name_of_list)):
    name_of_list[i] = something

but I can't remember the name and googling "iterate list" gets nothing.但我不记得名字和谷歌搜索“迭代列表”一无所获。

>>> a = [3,4,5,6]
>>> for i, val in enumerate(a):
...     print i, val
...
0 3
1 4
2 5
3 6
>>>

Yep, that would be the enumerate function!是的,那就是enumerate函数! Or more to the point, you need to do:或者更重要的是,您需要执行以下操作:

list(enumerate([3,7,19]))

[(0, 3), (1, 7), (2, 19)]

Here's another using the zip function.这是另一个使用zip函数的方法。

>>> a = [3, 7, 19]
>>> zip(range(len(a)), a)
[(0, 3), (1, 7), (2, 19)]

Here it is a solution using map function:这是使用 map 函数的解决方案:

>>> a = [3, 7, 19]
>>> map(lambda x: (x, a[x]), range(len(a)))
[(0, 3), (1, 7), (2, 19)]

And a solution using list comprehensions:以及使用列表推导式的解决方案:

>>> a = [3,7,19]
>>> [(x, a[x]) for x in range(len(a))]
[(0, 3), (1, 7), (2, 19)]

python enumerate function will be satisfied your requirements python enumerate函数将满足您的要求

result = list(enumerate([1,3,7,12]))
print result

output输出

[(0, 1), (1, 3), (2, 7),(3,12)]

If you have multiple lists, you can do this combining enumerate and zip :如果您有多个列表,您可以结合enumeratezip执行此操作:

list1 = [1, 2, 3, 4, 5]
list2 = [10, 20, 30, 40, 50]
list3 = [100, 200, 300, 400, 500]
for i, (l1, l2, l3) in enumerate(zip(list1, list2, list3)):
    print(i, l1, l2, l3)
Output: 输出:
 0 1 10 100 1 2 20 200 2 3 30 300 3 4 40 400 4 5 50 500

Note that parenthesis is required after i .请注意, i之后需要括号。 Otherwise you get the error: ValueError: need more than 2 values to unpack否则你会得到错误: ValueError: need more than 2 values to unpack

You are looking python enumerate function 您正在寻找python枚举函数

Do as below 做如下

something = list(enumerate([1,3,7,12])) print something something = list(enumerate([1,3,7,12]))打印内容

output [(0, 1), (1, 3), (2, 7),(3,12)] 输出[(​​0,1),(1,3),(2,7),(3,12)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM