用分隔符合并两个列表中的项目

时间:2019-07-13 01:14:57

标签: python-3.5

我有两个单独的列表,“ a”和“ b”。我正在尝试将它们合并在一起,以便显示两个列表中的项目,并在两者之间加一个连字符。

我尝试使用zip和join函数,但无法解决问题。

a = ['USA', 'Australia', 'Netherlands', 'Sweden', 'France', 'Spain']
b = ['Washington', 'Canberra', 'Amsterdam', 'Stockholm', 'Paris', 'Barcelona']
##I tried using zip 
c = CT = zip(a,b)
##I got: 
[('USA', 'Washington'),
 ('Australia', 'Canberra'),
 ('Netherlands', 'Amsterdam'),
 ('Sweden', 'Stockholm'),
 ('France', 'Paris'),
 ('Spain', 'Barcelona')] 
Tried to use join as well, but that didn't work



Ideally, the output should be:
USA-Washington
Australia-Canberra
Netherlands-Amesterdam
Sweden-Stockholm
France-Paris
Spain-Barcelona

Any help would be appreciated.

2 个答案:

答案 0 :(得分:0)

您可以对压缩项目应用列表理解:

[x + '-' + y for x,y in zip(a,b)]

答案 1 :(得分:0)

您可以将join应用于zip的每个结果。

c = ['-'.join(x) for x in zip(a, b)]

或者您可以使用for循环。

c = []
for i in range(min(len(a), len(b))):
    c.append('{}-{}'.format(a[i], b[i]))