如何遍历Python中两个或更多列表的项目的元组? [英] How do I iterate over the tuples of the items of two or more lists in Python?

查看:555
本文介绍了如何遍历Python中两个或更多列表的项目的元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具体来说,我有两个字符串列表,我想将它们组合成一个字符串,其中每一行是列表中的下两个字符串,以空格分隔:

Specifically, I have two lists of strings that I'd like to combine into a string where each line is the next two strings from the lists, separated by spaces:

a = ['foo1', 'foo2', 'foo3']
b = ['bar1', 'bar2', 'bar3']

我想要一个函数Combine_to_lines()返回:

I want a function combine_to_lines() that would return:

"""foo1 bar1
foo2 bar2
foo3 bar3"""

我承认我已经解决了这个问题,所以我将发布答案.但是也许其他人有更好的表现,或者看到我的缺点.

I admit I've already solved this problem, so I'm going to post the answer. But perhaps someone else has a better one or sees a flaw in mine.

更新:我在上面简化了我的示例.在我的实际问题中,以更复杂的方式格式化行,这要求解压缩从zip()返回的元组.但是对 mhawke 表示敬意,以获取此示例的最简单解决方案.

Update: I over-simplified my example above. In my real-world problem the lines were formatted in a more complicated manner that required the tuples returned from zip() to be unpacked. But kudos to mhawke for coming up to the simplest solution to this example.

推荐答案

不必解压缩和重新打包zip返回的元组:

It's not necessary to unpack and repack the tuples returned by zip:

'\n'.join(' '.join(x) for x in zip(a, b))

这篇关于如何遍历Python中两个或更多列表的项目的元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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