Reputation: 57
I want to sort short list like:
# we can have only 3 types of value: any string numeric value like '555', 'not found' and '' (can have any variation with these options)
row = ['not found', '', '555']
to
# numeric values first, 'not found' less prioritize and '' in the end
['555', 'not found', '']
I trying use
row.sort(key=lambda x: str(x).isnumeric() and not bool(x))
but it's not working
How can I sort it? (numeric values first, 'not found' less prioritize and '' in the end)
Upvotes: 0
Views: 915
Reputation: 531
This will sort your list and give 'not found'
a higher priority than ''
:
l = [int(a) for a in row if a.isnumeric()] # Or float(a)
l.sort()
row = [str(a) for a in l] +\
['not found'] * row.count('not found') +\
[''] * row.count('')
Upvotes: 0
Reputation: 325
Edit: Sorting non numeric values per ask
ar = [i for i in row if not i.isnumeric()]
ar.sort(reverse=True)
row = [i for i in row if i.isnumeric()] + ar
Upvotes: 1
Reputation: 117
This will do the trick too:
row = ['not found', '', 555, 1, '5' , 444]
print(row)
def func(x):
if str(x).isnumeric():
return 1/-int(x) # ordering numerics event if they are strings
elif str(x) == 'not found':
return 2
elif str(x) == '':
return 3
row2 = row.sort(key=func)
print(row)
Results:
['not found', '', 555, 1, '5', 444]
[1, '5', 444, 555, 'not found', '']
Upvotes: 0
Reputation: 124
def custom_sort(list):
L1 = []
L2 = []
L3 = []
for element in list:
if element.isnumeric():
L1.append(element)
if element == 'Not found':
L2.append(element)
else : L3.append(element)
L1.sort()
L1.append(L2).append(L3)
return L1
Upvotes: 1