如何配对两个清单? [英] How to pair up two lists?

查看:71
本文介绍了如何配对两个清单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我有两个数据列表,它们是从以下位置获得的:

I have two lists of data which are obtained from:

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

我想创建一个循环,将"xs"中的第一项和"ys"中的第一项打印出来.然后,我想循环播放并重复两个列表中的第二个项目,依此类推.

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.

我曾想过类似的事情:

for x in xs and y in ys:

for x in xs:
    for y in ys:

但这些似乎都无法达到预期的效果.

But neither of these seems to give the desired result.

推荐答案

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

Use the zip function, along with tuple unpacking:

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

根据您的情况,根据您需要xsys的用途,您可以直接通过csv.reader进行迭代:

In your case, depending on what you need the xs and ys for, you could have iterated through the csv.reader directly:

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

zip(xs, ys)行有效地反转了xs, ys = zip(*reader)行.

这篇关于如何配对两个清单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆