简体   繁体   English

如何遍历Python中的多个列表

[英]How to traverse multiple lists in Python

I have two equal length lists.我有两个等长的列表。 I want to traverse them both at the same time in order to perform some operation on each equivalently indexed item of each list.我想同时遍历它们,以便对每个列表的每个等效索引项执行一些操作。

It seems inefficient to create an index variable to iterate through the lists.创建索引变量来遍历列表似乎效率低下。

For example, this works:例如,这有效:

a=[1,2,3]
b=[7,8,9]
for i in range(0,len(a)):
  print(a[i],b[i])

But can I do it without the index?但是我可以在没有索引的情况下做到这一点吗?

I did find: Traversing multiple lists in django template in same for loop but it looks massively complicated for all I want to do and I have no idea what a django template is!我确实发现: 在同一个 for 循环中遍历 django 模板中的多个列表,但对于我想做的所有事情来说,它看起来非常复杂,我不知道 django 模板是什么!

In asking the question and searching some of the keywords I didn't understand, I came up with an example more simple than the one I found, equivalent to my examples above:在提问和搜索一些我不明白的关键字时,我想出了一个比我找到的更简单的例子,相当于我上面的例子:

a=[1,2,3]
b=[7,8,9]

for j in zip(a,b):
  print(j[0],j[1])

This works because zip collates the two lists into a list of lists.这是因为 zip 将这两个列表整理成一个列表列表。

print(list(zip(a,b)))
>>> [(1, 7), (2, 8), (3, 9)]

This is certainly a shortcut for coding, but I'm sure there must be an even more efficient way.这当然是编码的捷径,但我相信一定有更有效的方法。

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

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