简体   繁体   中英

Sort List of Tuples Containing Strings By First Element Float (Python)

I have a long list of tuples:

[...
(0.862, 'beehive', 'bug'),
(0.12, 'yard', 'property'),
(0.0, 'lake', 'mailbox'),
(0.37, 'maintenance', 'shears'),
(0.1666, 'summer', 'popsicle'),
(0.9, 'poplar', 'tree')
...]

and I need to sort this list descending by the float values. I know the Python automatically sorts lists by the first value, however even when I call sorted or even explicitly specify the first element, I haven't had success.

sorted(mylist) # doesn't sort the list at all

sorted(mylist, key = x[0]) # on this sort attempt I get "'str' object is not callable"

Can anyone provide detail as to why the list is still disorganized despite these sorting attempts and what might sort by floats in descending order?

sorted(..) returns a new list. What you are looking for is .sort(..) to sort the list inplace .

Furthermore you can use the reverse parameter to sort in descending order:

data.sort(reverse=True)  # sort the list inplace

This will return:

>>> data.sort(reverse=True)
>>> data
[(0.9, 'poplar', 'tree'), (0.862, 'beehive', 'bug'), (0.37, 'maintenance', 'shears'), (0.1666, 'summer', 'popsicle'), (0.12, 'yard', 'property'), (0.0, 'lake', 'mailbox')]

The default sorting of tuples will first sort on the first elements . If these are equal, it will consider the second element of each tuple and so on.

If you do not want this tie breaker, but use the original order in that case, you can use an itemgetter as key :

from operator import itemgetter

data.sort(reverse=True,key=itemgetter(0))  # sort the list inplace

You can use the same arguments with sorted(..) if you want to construct a new list that is sorted:

data_sorted = sorted(data,reverse=True)  # construct a new sorted list

Try this way :

data = [
(0.862, 'beehive', 'bug'),
(0.12, 'yard', 'property'),
(0.0, 'lake', 'mailbox'),
(0.37, 'maintenance', 'shears'),
(0.1666, 'summer', 'popsicle'),
(0.9, 'poplar', 'tree')
]

print(*reversed(sorted(data)))

Output :

(0.9, 'poplar', 'tree') (0.862, 'beehive', 'bug') (0.37, 'maintenance', 'shears') (0.1666, 'summer', 'popsicle') (0.12, 'yard', 'property') (0.0, 'lake', 'mailbox')

Or, You can follow another process :

>>> data = [
... (0.862, 'beehive', 'bug'),
... (0.12, 'yard', 'property'),
... (0.0, 'lake', 'mailbox'),
... (0.37, 'maintenance', 'shears'),
... (0.1666, 'summer', 'popsicle'),
... (0.9, 'poplar', 'tree')
... ]
>>> data.sort(key=lambda tup: tup[0], reverse = True)
>>> data
[(0.9, 'poplar', 'tree'), (0.862, 'beehive', 'bug'), (0.37, 'maintenance', 'shears'), (0.1666, 'summer', 'popsicle'), (0.12, 'yard', 'property'), (0.0, 'lake', 'mailbox')]
>>>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM