I have a list that looks like below:
list = ['8 4', '4 3', '15 8', '10 5', '']
I want to sort this by the first element of each pair in descending order. That is, my output should look like the below.
sortedlist = ['15 8', '8 4', '10 5', '4 3' '']
How do I achieve this?
CodePudding user response:
You can use str.split
and use first element of each pair.
lst = ['8 4', '4 3', '15 8', '10 5', '']
def key_sort(x):
try:
return int(x.split()[0]) # '8 4'.split() -> ['8', '4']
except IndexError:
# for handling empty string : `''`
return float('-inf')
lst.sort(key=key_sort, reverse = True)
print(lst)
Output:
['15 8', '10 5', '8 4', '4 3', '']
CodePudding user response:
With
lst = ['8 4', '4 3', '15 8', '10 5', '']
Try:
sorted(lst, key=lambda x: int(x.split()[0]) if len(x) else float("-inf"), reverse = True)
outputs:
['15 8', '10 5', '8 4', '4 3', '']
CodePudding user response:
Something like this: (use the helper sort_key)
L = ['8 4', '4 3', '15 8', '10 5']
def sort_key(x):
tp = x.split()
return -(int(tp[0])) #, int(tp[1]) <--- updated based on feedback
>>>sorted(L, key=sort_key)
['15 8', '10 5', '8 4', '4 3']