Can i integrate multiple lists in python?
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
how can I iterate through two lists in parallel in Python?
我有3个这样的列表:
1 2 3 | name = ['sam', 'john', 'napoleon', 'tanaka', 'ming'] country = ['USA', 'England', 'France', 'Japan', 'China'] age = [23, 41, 19, 16, 55] |
我想要一个输出,比如:
1 2 3 4 5 | sam; USA; 23 john; England; 41 napoleon; France; 19 tanaka; Japan; 16 ming; China; 55 |
任何帮助都会很好。提前谢谢
您可以使用
1 2 3 4 5 | 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)) |
或使用
1 2 3 | mapp=map(lambda x,y,z:";".join((x,y,str(z))),name,country,age) for x in mapp: print(x) |
输出:
1 2 3 4 5 | sam; USA; 23 john; England; 41 napoleon; France; 19 tanaka; Japan; 16 ming; China; 55 |
1 2 3 4 5 6 | name ="sam john napoleon tanaka ming".split() country ="USA England France Japan China".split() age = [23, 41, 19, 16, 55] print" ".join(["%s; %s %d" % (x) for x in zip(name,country,age)]) |
假设列表的长度相同:
1 2 | for i in range(len(name)): print '%s; %s; %s' %(name[i], country[i], age[i]) |
更新:这假设您使用的是python 3.x。对于2.x,使用xrange来提高总体性能。可选地:
1 2 | for i in range(len(name)): print '{0}; {1}; {2}'.format{name[i], country[i], age[i]} |
我的2分钱;
使用ITertools模块中的生成器:
1 2 3 | from itertools import izip nlist = ['%s; %s; %s' %t for t in izip(name, country, age)] |
如果你知道它们的长度相同,那么你可以这样做:
1 2 3 4 5 6 7 8 9 | 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++ |