Paul
Paul

Reputation: 5974

Sorting list of strings based on substring in each string

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?

Upvotes: 1

Views: 452

Answers (2)

Andrew Winterbotham
Andrew Winterbotham

Reputation: 1010

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

Upvotes: 1

Anshul Goyal
Anshul Goyal

Reputation: 76867

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']

Upvotes: 6

Related Questions