如何在 Python 中迭代两个或多个列表的项的元组? [英] How do I iterate over the tuples of the items of two or more lists in 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:
'
'.join(' '.join(x) for x in zip(a, b))
这篇关于如何在 Python 中迭代两个或多个列表的项的元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!