-3

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')]
bmaloney
  • 1
  • 1
  • How is that sorted? Which logic did you apply? – trincot May 18 '22 at 05:57
  • 1
    Does this answer your question? [How to sort a list of objects based on an attribute of the objects?](https://stackoverflow.com/questions/403421/how-to-sort-a-list-of-objects-based-on-an-attribute-of-the-objects) – moooeeeep May 18 '22 at 05:59
  • This data would be *vastly* easier to work with if you had actual numbers rather than strings. – jasonharper May 18 '22 at 06:01

2 Answers2

0

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')]
Mechanic Pig
  • 6,756
  • 3
  • 10
  • 31
0

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')]
ThatNerd
  • 31
  • 2
  • 2