'Need to sort this by the value but move the 0 to the end
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')]
Solution 1:[1]
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')]
Solution 2:[2]
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')]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ThatNerd |
| Solution 2 | Mechanic Pig |
