[英]Python: Merging two lists and present them as a string
I've done my research and got very close to solving my issue but I need a bit of help to cross the finish line! 我已经完成了研究,已经非常接近解决我的问题,但是我需要一点帮助才能越过终点!
I have two lists: 我有两个清单:
Countries = ["Germany", "UK", "France", "Italy"]
Base = ["2005","1298",1222","3990"]
Expected outcome: 预期结果:
"Germany (2005)", "UK (1298)", "France (1222)", "Italy (3990)"
My script: 我的剧本:
zipped = zip(Countries, Base)
Outcome: 结果:
[('Germany', '2005')", ('UK', '1298'), ('France', '1222'), ('Italy', '3990')]
So I'm close but I have no idea how to format it properly. 所以我接近了,但是我不知道如何正确格式化它。
Thanks 谢谢
You were almost there, you just need to use string formatting : 您就快到了,您只需要使用字符串格式即可 :
>>> ["{} ({})".format(x,y) for x,y in zip(Countries, Base)]
['Germany (2005)', 'UK (1298)', 'France (1222)', 'Italy (3990)']
Use str.join
: 使用
str.join
:
>>> print ", ".join('"{} ({})"'.format(x,y) for x,y in zip(Countries, Base))
"Germany (2005)", "UK (1298)", "France (1222)", "Italy (3990)"
Use itertools.izip
for memory efficient solution. 使用
itertools.izip
获得内存有效的解决方案。
In addition to Ashwini's solution , you can take advantage of the implicit zipping that map
performs on its arguments. 除了Ashwini的解决方案外 ,您还可以利用
map
对其参数执行的隐式压缩。
>>> ', '.join(map('"{} ({})"'.format, Countries, Base))
'"Germany (2005)", "UK (1298)", "France (1222)", "Italy (3990)"'
timeit
results indicate that this solution is faster that the one proposed by Ashwini: timeit
结果表明该解决方案比Ashwini提出的解决方案更快:
>>> from timeit import Timer as t
>>> t(lambda: ', '.join(map('"{} ({})"'.format, Countries, Base))).timeit()
4.5134528969464
>>> t(lambda: ", ".join(['"{} ({})"'.format(x,y) for x,y in zip(Countries, Base)])).timeit()
6.048398679161739
>>> t(lambda: ", ".join('"{} ({})"'.format(x,y) for x,y in zip(Countries, Base))).timeit()
8.722563482230271
This method uses map but forgoes string formatting in favor of another join and string concatenation: 此方法使用map,但放弃了字符串格式,而采用了另一种联接和字符串连接:
print ', '.join(map(lambda a: ' ('.join(a)+')', zip(Countries, Base))) #outputs string
print map(lambda a: ' ('.join(a)+')', zip(Countries, Base)) #outputs list
尝试这个
','.join([Countries[i]+'('+Base[i]+')' for i in range(len(Countries))])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.