0

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)

2
  • You stated the basic problem quite clearly: the order you want is not what sort supports, yet you somehow expect sort to do what you want. You need to define your own key function to produce the priorities as you define them. Alternately, filter the list into the three groupings you specify, sort each grouping, and concatenate the results. Commented Jun 18, 2020 at 16:39
  • I have added I solution with a function for sort(key=func) Commented Jun 18, 2020 at 16:52

4 Answers 4

1
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
Sign up to request clarification or add additional context in comments.

2 Comments

You can't do L1.append(L2).append(L3). Anyway, I think what you are actually trying to do here is L1.extend(L2); L1.extend(L3).
Actually didn't tried that. I amswered that from my smartphone. But thanks man
1

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

2 Comments

This solution actually doesn't take into account the fact that 'not found' should outrank '' in the sorted list.
@AdamBoinet right. I added that as a comment in one of the comments
0

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', '']

Comments

0

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('')

1 Comment

Or, even faster for the latter part: ['not found'] * row.count('not found') + [' '] * row.count(' ')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.