Python 如何配对两个列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16401906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:31:08  来源:igfitidea点击:

How to pair up two lists?

pythonlist

提问by user1813343

I'm a bit of a Python beginner so I apologise if this is a very basic question.

我是一个 Python 初学者,所以如果这是一个非常基本的问题,我深表歉意。

I have two lists of data which are obtained from:

我有两个数据列表,它们来自:

with filein as f:
        reader=csv.reader(f)
        xs, ys = zip(*reader)

I would like to create a loop which would take the first item in "xs" and the first item in "ys" and print them out. I would then like to loop back and repeat for the second item in both lists and so forth.

我想创建一个循环,它将获取“xs”中的第一项和“ys”中的第一项并将它们打印出来。然后我想循环并重复两个列表中的第二个项目等等。

I had thought something like:

我曾想过这样的事情:

for x in xs and y in ys:

Or

或者

for x in xs:
    for y in ys:

But neither of these seems to give the desired result.

但这些似乎都没有给出预期的结果。

回答by David Robinson

Use the zipfunction, along with tuple unpacking:

使用该zip函数以及元组解包:

for x, y in zip(xs, ys):
    print x, y

In your case, depending on what you need the xsand ysfor, you could have iterated through the csv.readerdirectly:

在您的情况下,根据您的需要xs和目的ys,您可以csv.reader直接遍历:

with filein as f:
    reader=csv.reader(f)
    for x, y in reader:
        print x, y

The zip(xs, ys)line was effectively reversing your xs, ys = zip(*reader)line.

zip(xs, ys)条线有效地逆转了你的xs, ys = zip(*reader)路线。

回答by Mark Tolonen

Use zip:

使用邮编

>>> L=[1,2,3]
>>> M=[4,5,6]
>>> for a,b in zip(L,M):
...   print(a,b)
...
1 4
2 5
3 6

回答by kiriloff

For a one line you can use combination of map()and lambda(). Look here if not familiar to this concepts.

对于一行,您可以使用map()和 的组合lambda()如果不熟悉这个概念,请看这里。

But be careful, you must be with python 3.x so that print is a function and can be used inside the lambda expression.

但要小心,你必须使用 python 3.x,以便 print 是一个函数并且可以在 lambda 表达式中使用。

>>> from __future__ import print_function
>>> l1 = [2,3,4,5]
>>> l2 = [6,7,3,8]
>>> list(map(lambda X: print(X[0],X[1]), list(zip(l1,l2))))

output

输出

2 6
3 7
4 3
5 8