1

I have a list like below:

 a = ['e8:04:62:23:57:d0\t2462\t-55\t[WPA2-PSK-CCMP][ESS]\tTest', '00:1b:2f:48:8b:f2\t2462\t-57\t[WPA2-PSK-CCMP-preauth][ESS]\tT_test', 'e8:04:62:23:4e:70\t2437\t-61\t[WPA2-PSK-CCMP][ESS]\tT_guest', 'e8:04:62:23:57:d1\t2462\t-53\t[ESS]\t', 'e8:04:62:23:4e:71\t2437\t-56\t[ESS]\t']

I want to sort the list based on the numbers after the third tab of each element, so in this case -55, -57, -61, -53 should change list order to -53, -55, -57, -61. Any way I have tried seems very convoluted (making a list of lists and so on). Should I be using a regex/pattern to simplify this?

2 Answers 2

6

You can pass in a custom lambda here to the sorted function to get the desired result:

>>> a = ['e8:04:62:23:57:d0\t2462\t-55\t[WPA2-PSK-CCMP][ESS]\tTest', '00:1b:2f:48:8b:f2\t2462\t-57\t[WPA2-PSK-CCMP-preauth][ESS]\tT_test', 'e8:04:62:23:4e:70\t2437\t-61\t[WPA2-PSK-CCMP][ESS]\tT_guest', 'e8:04:62:23:57:d1\t2462\t-53\t[ESS]\t', 'e8:04:62:23:4e:71\t2437\t-56\t[ESS]\t']
>>> sorted(a, key = lambda x: int(x.split("\t")[2]), reverse=True)
['e8:04:62:23:57:d1\t2462\t-53\t[ESS]\t', 'e8:04:62:23:57:d0\t2462\t-55\t[WPA2-PSK-CCMP][ESS]\tTest', 'e8:04:62:23:4e:71\t2437\t-56\t[ESS]\t', '00:1b:2f:48:8b:f2\t2462\t-57\t[WPA2-PSK-CCMP-preauth][ESS]\tT_test', 'e8:04:62:23:4e:70\t2437\t-61\t[WPA2-PSK-CCMP][ESS]\tT_guest']
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, that is much more concise and "pythonic" than what I had done.
Don't forget to use int.(for get ride of lexicographicaly order)
This solution is buggy, you must convert it to int read this question: stackoverflow.com/questions/3270680/…
Thanks I can see there is a mistake here and if I use int the solution doesn't work, it will sort them backwards from what I want with -61 first. Must add reverse=True as well as int.
1
def make_sorted_list(l):
    sorted_list = []
    sorted_vals = sorted([int(s.split('\t')[2]) for s in l], reverse=True)
    for val in sorted_vals:
        for s in l:
            if int(s.split('\t')[2]) == val:
                sorted_list.append(s)
    return sorted_list

Comments

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.