如何将两个列表的元素一起打印

时间:2019-04-04 23:16:28

标签: python-3.x list for-loop

我有两个具有不同元素数量的列表。我想用第二个列表的每个元素打印第一个列表的每个元素,依此类推。

a = [1,2,3,4,5]
b = ["banana", "orange", "pear"]

我想要获得的输出:

1 banana

1 orange

1 pear

2 banana 

2 orange

以此类推。

我尝试过:

a = [1,2,3,4,5]
b = ["banana", "orange", "pear"]

for i,k in zip(a,b):
    print(i, k)

但我得到以下输出:

1 banana
2 orange
3 pear

Process finished with exit code 0

1 个答案:

答案 0 :(得分:2)

您正在寻找itertools.product

>>> import itertools as it
>>> a = [1,2,3,4,5]
>>> b = ["banana", "orange", "pear"]
>>> for x in it.product(a, b):
...     print(x)
... 
(1, 'banana')
(1, 'orange')
(1, 'pear')
(2, 'banana')
(2, 'orange')
(2, 'pear')
(3, 'banana')
(3, 'orange')
(3, 'pear')
(4, 'banana')
(4, 'orange')
(4, 'pear')
(5, 'banana')
(5, 'orange')
(5, 'pear')