问题:在Python中使用索引迭代列表
我可以发誓我已经看过需要一个列表的函数(或方法),像这样[3, 7, 19]
并将其放入可重复的元组列表中,如下所示:[(0,3), (1,7), (2,19)]
使用它代替:
for i in range(len(name_of_list)):
name_of_list[i] = something
但我记不起来名字了,谷歌搜索“迭代列表”一无所获。
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:
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.
回答 0
>>> a = [3,4,5,6]
>>> for i, val in enumerate(a):
... print i, val
...
0 3
1 4
2 5
3 6
>>>
>>> a = [3,4,5,6]
>>> for i, val in enumerate(a):
... print i, val
...
0 3
1 4
2 5
3 6
>>>
回答 1
是的,那就是enumerate
功能!或更重要的是,您需要执行以下操作:
list(enumerate([3,7,19]))
[(0, 3), (1, 7), (2, 19)]
Yep, that would be the enumerate
function! Or more to the point, you need to do:
list(enumerate([3,7,19]))
[(0, 3), (1, 7), (2, 19)]
回答 2
这是使用该zip
函数的另一个。
>>> a = [3, 7, 19]
>>> zip(range(len(a)), a)
[(0, 3), (1, 7), (2, 19)]
Here’s another using the zip
function.
>>> a = [3, 7, 19]
>>> zip(range(len(a)), a)
[(0, 3), (1, 7), (2, 19)]
回答 3
这是使用map函数的解决方案:
>>> a = [3, 7, 19]
>>> map(lambda x: (x, a[x]), range(len(a)))
[(0, 3), (1, 7), (2, 19)]
以及使用列表推导的解决方案:
>>> a = [3,7,19]
>>> [(x, a[x]) for x in range(len(a))]
[(0, 3), (1, 7), (2, 19)]
Here it is a solution using map function:
>>> 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)]
回答 4
python enumerate
函数将满足您的要求
result = list(enumerate([1,3,7,12]))
print result
输出
[(0, 1), (1, 3), (2, 7),(3,12)]
python enumerate
function will be satisfied your requirements
result = list(enumerate([1,3,7,12]))
print result
output
[(0, 1), (1, 3), (2, 7),(3,12)]
回答 5
如果您有多个列表,则可以将合并enumerate
和zip
:
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)
输出:
0 1 10 100
1 2 20 200
2 3 30 300
3 4 40 400
4 5 50 500
请注意,必须在后面加上括号i
。否则会出现错误:ValueError: need more than 2 values to unpack
If you have multiple lists, you can do this combining enumerate
and zip
:
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
. Otherwise you get the error: ValueError: need more than 2 values to unpack