Home > Mobile >  Need to sort this by the value but move the 0 to the end
Need to sort this by the value but move the 0 to the end

Time:05-18

It currently looks like this unsorted.

[('391', '0'), ('411', '0.00'), ('174', '4'), ('734', '8.753'),('512', '6.3'),('700', '5.34'),]

I need to make it look like this if possible.

[('174', '4'),('700', '5.34'),('512', '6.3'),('734', '8.753'),('391', '0'),('411', '0.00')]

CodePudding user response:

You can accomplish this using the .sort() method, first sorting normally, then sorting so that values equal to 0 are moved to the end.

my_list = [('391', '0'), ('411', '0.00'), ('174', '4'), ('734', '8.753'),('512', '6.3'),('700', '5.34'),]
my_list.sort(key=lambda x: x[1])
my_list.sort(key=lambda x: float(x[1]) == 0)
print(my_list)
# Output:
# [('174', '4'), ('700', '5.34'), ('512', '6.3'), ('734', '8.753'), ('391', '0'), ('411', '0.00')]

CodePudding user response:

Get the key with a simple function:

>>> lst = [('391', '0'), ('411', '0.00'), ('174', '4'), ('734', '8.753'),('512', '6.3'),('700', '5.34'),]
>>> def get_key(x):
...     f = float(x[1])
...     return f if f else float('inf')
...
>>> sorted(lst, key=get_key)
[('174', '4'), ('700', '5.34'), ('512', '6.3'), ('734', '8.753'), ('391', '0'), ('411', '0.00')]
  • Related