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?

Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
Paul
  • 5,756
  • 6
  • 48
  • 78

2 Answers2

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']
Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
  • 1
    Thank you, that is much more concise and "pythonic" than what I had done. – Paul Jun 25 '15 at 10:48
  • 1
    Don't forget to use `int`.(for get ride of lexicographicaly order) – Mazdak Jun 25 '15 at 10:49
  • 1
    This solution is buggy, you must convert it to `int` read this question: http://stackoverflow.com/questions/3270680/how-does-python-compare-string-and-int – Elisha Jun 25 '15 at 10:58
  • 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`. – Paul Jun 25 '15 at 11:06
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
Andrew Winterbotham
  • 1,000
  • 7
  • 13