Boosted_d16
Boosted_d16

Reputation: 14062

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

Upvotes: 0

Views: 81

Answers (4)

Harry.Chen
Harry.Chen

Reputation: 1610

try this

','.join([Countries[i]+'('+Base[i]+')' for i in range(len(Countries))])

Upvotes: 0

Matthew Graves
Matthew Graves

Reputation: 3284

This method uses map but forgoes string formatting in favor of another join and string concatenation:

print ', '.join(map(lambda a: ' ('.join(a)+')', zip(Countries, Base))) #outputs string

print map(lambda a: ' ('.join(a)+')', zip(Countries, Base)) #outputs list

Upvotes: 0

Volatility
Volatility

Reputation: 32300

In addition to Ashwini's solution, you can take advantage of the implicit zipping that map performs on its arguments.

>>> ', '.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:

>>> 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

Upvotes: 5

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250941

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:

>>> 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.

Upvotes: 5

Related Questions