user3149650
user3149650

Reputation: 203

sort list consisting of numbers and string values

I don't whether it's possible at all but I have got a list consisting of many values like

list = ["0.75543 blue", "0.5454 red", "0.113424 blue", "0.9993233 red" and so on] and so on. 

In other words I have values between 0 and 1 and two labels blue and red. When I click array.sort() it doesn't sort them properly as the values in the list are strings. I want to be able to sort the list based on the values only properly (independent of the label). Is that possible?

Upvotes: 0

Views: 87

Answers (1)

mdml
mdml

Reputation: 22882

Yes, you can sort just based on the numeric value in the first part of the string. Just pass sort a key that extracts the number from each string.

Demo

>>> L = ["0.75543 blue", "0.5454 red", "0.113424 blue", "0.9993233 red"]
>>> L.sort(key=lambda l: float(l.split()[0]))
>>> L
['0.113424 blue', '0.5454 red', '0.75543 blue', '0.9993233 red']

Also, depending on what you're doing, you may find it easier to store the value-label pairs as tuples. Then, sorting is even easier (and arguably more intuitive):

>>> L = [(0.75543, "blue"), (0.5454, "red"), (0.113424, "blue"), (0.9993233, "red")]
>>> L.sort(key=lambda t: t[0])
>>> L
[(0.113424, 'blue'), (0.5454, 'red'), (0.75543, 'blue'), (0.9993233, 'red')]

Finally, please don't name your lists list; list is a built-in type and function in Python (see @2rs2ts's comment).

Upvotes: 6

Related Questions