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]
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.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With