Python:合并两个列表并将它们显示为字符串

Boo*_*d16 0 python merge zip list

我完成了我的研究并且非常接近解决我的问题,但我需要一些帮助才能越过终点线!

我有两个清单:

Countries = ["Germany", "UK", "France", "Italy"]
Base = ["2005","1298",1222","3990"] 
Run Code Online (Sandbox Code Playgroud)

预期结果:

"Germany (2005)", "UK (1298)", "France (1222)", "Italy (3990)" 
Run Code Online (Sandbox Code Playgroud)

我的剧本:

zipped = zip(Countries, Base)
Run Code Online (Sandbox Code Playgroud)

结果:

[('Germany', '2005')", ('UK', '1298'), ('France', '1222'), ('Italy', '3990')] 
Run Code Online (Sandbox Code Playgroud)

所以我很接近,但我不知道如何正确格式化它.

谢谢

Ash*_*ary 5

你几乎就在那里,你只需要使用字符串格式:

>>> ["{} ({})".format(x,y) for x,y in zip(Countries, Base)]
['Germany (2005)', 'UK (1298)', 'France (1222)', 'Italy (3990)']
Run Code Online (Sandbox Code Playgroud)

用途str.join:

>>> print ", ".join('"{} ({})"'.format(x,y) for x,y in zip(Countries, Base))
"Germany (2005)", "UK (1298)", "France (1222)", "Italy (3990)"
Run Code Online (Sandbox Code Playgroud)

使用itertools.izip的内存有效的解决方案.


Vol*_*ity 5

除了Ashwini的解决方案之外,您还可以利用map对其参数执行的隐式压缩.

>>> ', '.join(map('"{} ({})"'.format, Countries, Base))
'"Germany (2005)", "UK (1298)", "France (1222)", "Italy (3990)"'
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)