【问题标题】:Sort a list by specific location in string按字符串中的特定位置对列表进行排序
【发布时间】: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


【解决方案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']

【讨论】:

    【解决方案2】:

    您可以使用lambda expression 并尝试

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

    列表中的每个字符串都根据_ 的出现进行拆分,并考虑对第二部分进行排序。

    但如果字符串不是您期望的格式,这可能不起作用。

    【讨论】:

    • @J...S:感谢您的快速回答。我不是 100% 确定字符串的第一部分是否总是看起来像我期望的那样,但我确信最后一部分总是看起来这种模式。因此,为了确保它适用于我的情况,我将其更改为 sort(key=lambda x: x.split('_')[-2])。在我的特殊情况下,我更喜欢使用“sort()”,因为我必须确保列表在完成后排序
    • 对于它的价值,这是可行的,因为 lambda 函数实际上做了你在原始函数中忘记做的同样的事情,return 值:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-27
    • 2021-06-10
    • 2017-05-31
    • 1970-01-01
    • 2018-07-02
    • 2013-01-02
    • 2014-04-15
    相关资源
    最近更新 更多