Skip to main content
 首页 » 编程设计

python之组合和循环遍历列表 python

2025年05月04日13linjiqin

first_name = ["Johnny", "Joseph", "Mary"] 
third_name = ["Mendez", "Nash", "Johanson"] 
second_name = ["John", "Allen", "Ann"] 
 
 
for i in first_name: 
    for x in second_name: 
        for y in third_name: 
            names = i + x + y 

我们如何制作输出:

[Johnny John Mendez, Joseph Allen Nash, Mary Ann Johanson] 

因为当我循环遍历所有列表时,我得到了困惑的名字。我们如何确定名称的顺序。 first_name second_name third_name?

请您参考如下方法:

使用zip() :

for first, second, third in zip(first_name, second_name, third_name): 
    print "{} {} {}".format(first, second, third) 

zip 函数同时遍历三个列表,并在每次迭代时从每个列表中取出相应的元素。