Python-同时迭代2个列表

发布于 2024-09-27 20:22:44 字数 448 浏览 2 评论 0原文

可能的重复:
如何并行迭代两个列表?

我有 2列表:

l = ["a", "b", "c"]
m = ["x", "y", "z"]

我想同时遍历两者,如下所示:

for e, f in l, m:
    print e, f

必须表明:

a x
b y
c z

问题是这是完全非法的。我怎样才能做这样的事情? (以 Pythonic 的方式)

Possible Duplicate:
How to iterate through two lists in parallel?

I have 2 lists:

l = ["a", "b", "c"]
m = ["x", "y", "z"]

And I want to iterate through both at the same time, something like this:

for e, f in l, m:
    print e, f

Must show:

a x
b y
c z

The thing is that is totally illegal. How can I do something like this? (In a Pythonic way)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

灯角 2024-10-04 20:22:44

查看 itertools izip。它看起来像这样

for i,j in izip( mylistA, mylistB ):
    print i + j

zip 函数也可以工作,但 izip 创建一个迭代器,它不会强制创建第三个列表。

Look at itertools izip. It'll look like this

for i,j in izip( mylistA, mylistB ):
    print i + j

The zip function will also work but izip creates an iterator which does not force the creation of a third list.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文