The first task was to join the party names with their odds.

The second challenge was to bring that list into a delimited string.

It took me a few goes to land the ideal approach

Let's start with some play data

names = ['Alpha', 'Beta', 'Gamma', 'Delta'] amounts = [1.20, 4.50, 151, 19.50]

My first go at combining the party names with their odds.

In [19]: [' '.join([a, str(b)]) for a, b in zip(names, amounts)] Out[19]: ['Alpha 1.2', 'Beta 4.5', 'Gamma 151', 'Delta 19.5']

My second attempt

In [20]: [' '.join([a, '$'+ str(b)]) for a, b in zip(names, amounts)] Out[20]: ['Alpha $1.2', 'Beta $4.5', 'Gamma $151', 'Delta $19.5']

My third attempt - this looks about right

In [21]: ['{} ${:.2f}'.format(a, b) for a, b in zip(names, amounts)] Out[21]: ['Alpha $1.20', 'Beta $4.50', 'Gamma $151.00', 'Delta $19.50']

Now, to get that into a delimited string. Voila!

In [22]: ', '.join(['{} ${:.2f}'.format(a, b) for a, b in zip(names, amounts)]) Out[22]: 'Alpha $1.20, Beta $4.50, Gamma $151.00, Delta $19.50'

## No comments:

## Post a Comment