Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort brackets after alphanumeric characters?

Tags:

python

Working in Python 3:

a = ['(', 'z', 'a', '1', '{']
a.sort()
a
['(', '1', 'a', 'z', '{']

How can I sort the list so that alphanumeric characters come before punctuation characters:

a = ['(', 'z', 'a', '1', '{']
a.custom_sort()
a
['1', 'a', 'z', '(', '{']

(Actually I don't care about the order of the last two characters.)

This seems surprisingly difficult!

I understand that Python sorts asciibetically, and I'm looking for a human-readable sort. I found natsort but it only seems to deal with numbers.

like image 638
Richard Avatar asked Jun 08 '26 11:06

Richard


1 Answers

You can use a key function for sort that returns a tuple to test if a given character is alphanumeric and use the character's lexicographical order as a secondary sorting key:

a.sort(key=lambda c: (not c.isalnum(), c))
like image 95
blhsing Avatar answered Jun 12 '26 13:06

blhsing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!