问题:在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

如果您有多个列表,则可以将合并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)
输出:
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


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。