2

可能重复:
如何在 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

任何帮助都会很棒。提前致谢

4

5 回答 5

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
于 2012-07-12T16:21:22.267 回答
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)])
于 2012-07-12T16:25:08.580 回答
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]}
于 2012-07-12T16:24:37.217 回答
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++
于 2012-07-12T16:27:11.780 回答
0

我的 2 美分 ;-)

使用来自 itertools 模块的生成器:

from itertools import izip

nlist = ['%s; %s; %s' %t for t in izip(name, country, age)]
于 2012-07-12T16:30:41.853 回答