可能重复:
how can I iterate through two lists in parallel in Python?
我有3个这样的列表:
name = ['sam', 'john', 'napoleon', 'tanaka', 'ming']
country = ['USA', 'England', 'France', 'Japan', 'China']
age = [23, 41, 19, 16, 55]
我希望输出如下:
sam; USA; 23
john; England; 41
napoleon; France; 19
tanaka; Japan; 16
ming; China; 55
任何帮助都会很棒。 提前谢谢
答案 0 :(得分:10)
您可以使用zip()
:
name = ['sam', 'john', 'napoleon', 'tanaka', 'ming']
country = ['USA', 'England', 'France', 'Japan', 'China']
age = [23, 41, 19, 16, 55]
for x,y,z in zip(name,country,age):
print("{0}; {1}; {2}".format(x,y,z))
或使用map()
:
mapp=map(lambda x,y,z:"; ".join((x,y,str(z))),name,country,age)
for x in mapp:
print(x)
<强>输出:强>
sam; USA; 23
john; England; 41
napoleon; France; 19
tanaka; Japan; 16
ming; China; 55
答案 1 :(得分:3)
name = "sam john napoleon tanaka ming".split()
country = "USA England France Japan China".split()
age = [23, 41, 19, 16, 55]
print "\n".join(["%s; %s %d" % (x) for x in zip(name,country,age)])
答案 2 :(得分:1)
假设列表长度相同:
for i in range(len(name)):
print '%s; %s; %s' %(name[i], country[i], age[i])
更新:这假设你使用的是Python 3.x.对于2.x,使用xrange进行一般性能改进。可替换地:
for i in range(len(name)):
print '{0}; {1}; {2}'.format{name[i], country[i], age[i]}
答案 3 :(得分:0)
如果你知道它们都具有相同的长度,那么你可以这样做:
name = ['sam', 'john', 'napoleon', 'tanaka', 'ming']
country = ['USA', 'England', 'France', 'Japan', 'China']
age = [23, 41, 19, 16, 55]
i = 0
for n in name:
print name[i] + '; ' + country[i] + '; ' + str(age[i])
i++
答案 4 :(得分:0)
我的2美分; - )
使用itertools模块中的生成器:
from itertools import izip
nlist = ['%s; %s; %s' %t for t in izip(name, country, age)]