按字符串中的特定位置对列表排序

2024-04-19 14:29:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串列表,我只想按字符串的特定部分排序,而不是按整个字符串排序。你知道吗

我只想把整个列表的最后一部分放在第二部分 当我使用常规sort()函数时,我有一个问题,它使用完整的字符串值进行排序。 我试过使用'key='选项和split('''''),但不知何故,我无法让它工作。你知道吗

# 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)

我当前收到以下错误消息: TypeError: '<' not supported between instances of 'NoneType' and 'NoneType'

我想将列表排序为:['/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']


Tags: topathkey字符串列表排序filesprofile
2条回答

你可以用lambda expression试试

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

列表中的每个字符串根据_的出现情况进行拆分,第二部分考虑排序。你知道吗

但是,如果字符串的格式不是您期望的格式,那么这可能不起作用。你知道吗

如果没有返回要拆分的值,则需要从sortprofiles函数返回该值,然后函数将按预期工作!你知道吗

前面您没有返回任何内容,这相当于返回None,当您尝试在None上运行类似于<的比较运算符时,会得到异常TypeError: '<' not supported between instances of 'NoneType' and 'NoneType'

所以下面的方法就行了

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))

然后输出

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

相关问题 更多 >