【发布时间】:2019-09-20 15:18:00
【问题描述】:
我有一个字符串列表,我想只按字符串的特定部分排序,而不是完整的字符串。
我想对整个列表进行排序,只关注倒数第二部分 当我使用常规的 sort() 函数时,我遇到的问题是它使用完整的字符串值进行排序。 我尝试使用带有 split('_') 的 'key=' 选项,但不知何故我无法让它工作。
# 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']
【问题讨论】:
-
你需要
return函数sortprofiles的值,在下面查看我的答案:) @nsolthe
标签: python python-3.x string list sorting