我有一个字符串列表,我只想按字符串的特定部分排序,而不是按整个字符串排序。你知道吗
我只想把整个列表的最后一部分放在第二部分 当我使用常规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']
你可以用lambda expression试试
列表中的每个字符串根据
_
的出现情况进行拆分,第二部分考虑排序。你知道吗但是,如果字符串的格式不是您期望的格式,那么这可能不起作用。你知道吗
如果没有返回要拆分的值,则需要从
sortprofiles
函数返回该值,然后函数将按预期工作!你知道吗前面您没有返回任何内容,这相当于返回
None
,当您尝试在None上运行类似于<
的比较运算符时,会得到异常TypeError: '<' not supported between instances of 'NoneType' and 'NoneType'
所以下面的方法就行了
然后输出
相关问题 更多 >
编程相关推荐