![]() |
Sorting lists prioritizing letters before numbers - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Sorting lists prioritizing letters before numbers (/thread-14242.html) |
Sorting lists prioritizing letters before numbers - Ratherfastmofo - Nov-21-2018 Hi guys, I'm a very new coder so your help means a lot. I'm trying to sort a list which unsorted might look like this: 001 123 001 Beta 123 402 123 403 123 402 CxR 123 192 UqS 123 001 Alpha 123 309 223 001 038 007 Bond 123 I want to sort this list so that the first three characters are sorted by number, but after that letters are prioritized in sorting. Thus i want the code to return the list sorted like so: 001 Alpha 123 001 Beta 123 001 038 001 123 007 Bond 123 192 UqS 123 309 223 402 CxR 123 402 123 403 123 How do i sort a list like so? Thanks, guys. RE: Sorting lists prioritizing letters before numbers - Gribouillis - Nov-21-2018 Ratherfastmofo Wrote:i want the code to return the list sorted like soPlease post the code to show what it currently returns. RE: Sorting lists prioritizing letters before numbers - Ratherfastmofo - Nov-21-2018 (Nov-21-2018, 09:43 AM)Gribouillis Wrote:Ratherfastmofo Wrote:i want the code to return the list sorted like soPlease post the code to show what it currently returns. Currently I've just used the sorted() function to sort a list in the usual pattern. I just want to hear weather there is a way to customize the sorting priorities in the given pattern. RE: Sorting lists prioritizing letters before numbers - stranac - Nov-21-2018 You'll need to write a custom key function. You can learn more in the Sorting HOW TO. RE: Sorting lists prioritizing letters before numbers - DeaD_EyE - Nov-21-2018 This key function should help. Maybe it can be optimized. def key(text): offset = ord('z') + 1 # getting the first 3 chars and convert it to int result = [int(text[:3])] # iterate over the rest. Whitespace is excluded for char in text[4:]: if char.isdigit(): # Add 122 to integer to get a lower prio result.append(int(char) + offset) else: # otherwise just return the ord of char result.append(ord(char)) # result is a list return resultThe sort function works as follows: For each element, the key-function is called with this element. The returned value is a list. A list is sorted by first element, then by second an so on.. The key function just modifies the values for integer, but not for normal letters and other symbols. I guess it can be optimized. This is just the first shoot. RE: Sorting lists prioritizing letters before numbers - woooee - Nov-21-2018 Split the list into two lists, one containing the alpha lines and one containing the number lines. Sort each one. Merge the number list to the alpha list. |