简体   繁体   中英

Sort a list by specific location in string

I've got a list of strings and I want to sort this by a specific part of the string only, not the full string.

I would like to sort the entire list only focusing on the second last part When I use the regular sort() functions I have the issue that it sorts using the full string value. I've tried using the 'key=' option with split('_') but somehow I am not able to get it working.

# Key to sort profile files
def sortprofiles(item):
        item.split('_')[-2]

# Input
local_hostname = 'ma-tsp-a01'
profile_files = ['/path/to/file/TSP_D01_ma-tsp-a01\n', \
'/path/to/file/TSP_D02_ma-tsp-a02\n', \
'/path/to/file/TSP_ASCS00_ma-tsp-a01\n', \
'/path/ato/file/TSP_DVEBMGS03_ma-tsp-a03\n', \
'/path/to/file/TSP_DVEBMGS01_ma-tsp-a01\n']
# Do stuff
profile_files = [i.split()[0] for i in profile_files]
profile_files.sort(key=sortprofiles)
print(profile_files)

I currently get the following error message: TypeError: '<' not supported between instances of 'NoneType' and 'NoneType'

I would like to get the list sorted as: ['/path/to/file/TSP_ASCS00_ma-tsp-a01', '/path/to/file/TSP_D01_ma-tsp-a01', '/path/to/file/TSP_D02_ma-tsp-a02', '/path/to/file/TSP_DVEBMGS01_ma-tsp-a01', '/path/ato/file/TSP_DVEBMGS03_ma-tsp-a03']

You could use a lambda expression and try

profile_files = sorted(profile_files, key=lambda x: x.split('_')[1])

Each string in the list is split based on the occurrence of _ and the second part is considered for sorting.

But this may not work if the strings are not in the format that you expect.

You are not returning the value on how you want to split on, you need to return it from sortprofiles function and then your function will work as expected!

Earlier you were not returning anything, which is equivalent to returning None and when you try to run a comparison operator like < on None, you get the exception TypeError: '<' not supported between instances of 'NoneType' and 'NoneType'

So the below will work

def sortprofiles(item):
    #You need to return the key you want to sort on
    return item.split('_')[-2]

local_hostname = 'ma-tsp-a01'
profile_files = ['/path/to/file/TSP_D01_ma-tsp-a01\n',
'/path/to/file/TSP_D02_ma-tsp-a02\n',
'/path/to/file/TSP_ASCS00_ma-tsp-a01\n',
'/path/ato/file/TSP_DVEBMGS03_ma-tsp-a03\n',
'/path/to/file/TSP_DVEBMGS01_ma-tsp-a01\n']

print(sorted(profile_files, key=sortprofiles))

The output will then be

['/path/to/file/TSP_ASCS00_ma-tsp-a01\n', '/path/to/file/TSP_D01_ma-tsp-a01\n', '/path/to/file/TSP_D02_ma-tsp-a02\n', '/path/to/file/TSP_DVEBMGS01_ma-tsp-a01\n', '/path/ato/file/TSP_DVEBMGS03_ma-tsp-a03\n']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM