如何在 python 中使用 zip 函数合并两个列表的元素?

How to combine the elements of two lists using zip function in python?

我有两个不同的列表,我想知道如何让一个列表的每个元素与另一个列表的每个元素一起打印。我知道我可以使用两个 for 循环(每个循环用于一个列表),但是我想使用 zip() 函数,因为我将在此 for loop 中做更多的事情,我将需要 [=23] =]并行迭代.

因此我尝试了以下操作,但输出如下所示。

lasts = ['x', 'y', 'z']
firsts = ['a', 'b', 'c']

for last, first in zip(lasts, firsts):
    print (last, first, "\n")

输出:

x a 
y b 
z c 

预期输出:

x a
x b
x c
y a
y b
y c
z a
z b
z c

老实说,我认为您无法使用 zip 来完成此操作,因为您正在寻找另一种行为。 使用语法糖并使其与 zip 一起工作只会使您的调试体验无效。

但如果你愿意拖着我的膝盖:

zip([val for val in l1 for _ in range(len(l2))],
    [val for _ in l1 for val in l2])

首先复制第一个列表以获得 xxxyyyzzz 并使用 abcabcabc 复制第二个列表

for last,first in [(l,f) for l in lasts for f in firsts]:
     print(last, first, "\n")

我相信您正在寻找的函数是 itertools.product:

lasts = ['x', 'y', 'z']
firsts = ['a', 'b', 'c']

from itertools import product
for last, first in product(lasts, firsts):
    print (last, first)

x a
x b
x c
y a
y b
y c
z a
z b
z c

另一个生成迭代器的替代方法是使用嵌套理解:

iPairs=( (l,f) for l in lasts for f in firsts)
for last, first in iPairs:
    print (last, first)