user1566200
user1566200

Reputation: 1838

Calculations on Python lists?

I have this list:

[[54.1757, 57.7807], [61.5786, 64.1535], [67.9584, 83.0], [104.4185, 120.377]]

What I want to do is to translate this list into a format where I have a string:

first_number:second_number-first_number

for each pair in my list. So for the first pair, I would get the following string:

"54.1757:3.605"

Any suggestions on the best way to implement this?

Upvotes: 0

Views: 60

Answers (2)

ronakg
ronakg

Reputation: 4212

This is very easy to do using list comprehension.

>>> list = [[54.1757, 57.7807], [61.5786, 64.1535], [67.9584, 83.0], [104.4185, 120.377]]
>>>
>>> [ {x:y-x} for x, y in list ]
[{54.1757: 3.605000000000004}, {61.5786: 2.5748999999999924}, {67.9584: 15.041600000000003}, {104.4185: 15.9585}]
>>>

Upvotes: 0

mdml
mdml

Reputation: 22882

You can do this with a list comprehension:

In [1]: arr = [[54.1757, 57.7807], [61.5786, 64.1535], [67.9584, 83.0], [104.4185, 120.377]]

In [2]: arr2 = [ "{}:{}".format(a, a-b) for a, b in arr ]

In [3]: arr2
Out[3]:
['54.1757:-3.605', '61.5786:-2.5749', '67.9584:-15.0416', '104.4185:-15.9585']

Upvotes: 2

Related Questions