Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort list based on it's corresponding ascii values?

list1 = ['a', 'b', 'c', 'd', 'ab', 'bc', 'cd', 'abc', 'bcd', 'abcd']

How to sort this list values based on it's corresponding ascii values ?

sorted(list1, key=len,reverse=True)
Outputs      : ['abcd', 'abc', 'bcd', 'ab', 'bc', 'cd', 'a', 'b', 'c', 'd']
ascii values : [394, 294, 297, 195, 197, 199, 97, 98, 99, 100]

Tried this, which prints ascii values. But may be I required to store in dictionary. And then sort it and then extract. Any simple and optimal way of handling it (may be with mapping or not using any other lists/dicts).

for i in list1:
    print(i, sum(map(ord, i)))

Expected output based on ascii (descending order):

['abcd', 'bcd','abc','cd','bc','ab', 'd', 'c', 'b','a']
[ 394  ,  297,  294,  199, 197, 195, 100,  99,  98, 97]
like image 868
StackGuru Avatar asked Oct 16 '25 16:10

StackGuru


2 Answers

You can just use your ascii conversion function as the sort key to sort by those values:

list1 = ['a', 'b', 'c', 'd', 'ab', 'bc', 'cd', 'abc', 'bcd', 'abcd']

print(sorted(list1, key = lambda s: sum(map(ord, s)), reverse=True))

Output

['abcd', 'bcd', 'abc', 'cd', 'bc', 'ab', 'd', 'c', 'b', 'a']

Note that this will leave values in list1 which have the same ascii value sorted as they were in the original list (since python sort is stable). You may want to sort them in the same order as the rest of the list (so for example 'da' would sort before 'ad'), in which case you can just add the current value to the key function so that it sorts first by the ascii value and then the actual string:

sorted(list1, key = lambda s: (sum(map(ord, s)), s), reverse=True)

Thanks to @superbrain for the input to these edits.

like image 172
Nick Avatar answered Oct 19 '25 12:10

Nick


list1 = ['a', 'b', 'c', 'd', 'ab', 'bc', 'cd', 'abc', 'bcd', 'abcd']

print(sorted(list1, reverse=True, key=lambda k: sum(ord(ch) for ch in k)))

Prints:

['abcd', 'bcd', 'abc', 'cd', 'bc', 'ab', 'd', 'c', 'b', 'a']
like image 35
Andrej Kesely Avatar answered Oct 19 '25 12:10

Andrej Kesely