首页 > 解决方案 > PYTHON 使用空值、字符串和数值对列表进行排序

问题描述

我想对短列表进行排序,例如:

# we can have only 3 types of value: any string numeric value like '555', 'not found' and '' (can have any variation with these options)
row = ['not found', '', '555']

# numeric values first, 'not found' less prioritize and '' in the end
['555', 'not found', ''] 

我尝试使用

row.sort(key=lambda x: str(x).isnumeric() and not bool(x))

但它不工作

我该如何排序?(数值在前,“未找到”优先级较低,最后是“”)

标签: pythonpython-3.xlistsorting

解决方案


def custom_sort(list):
    L1 = []
    L2 = []
    L3 = []
    for element in list:
        if element.isnumeric():
            L1.append(element)
        if element == 'Not found':
            L2.append(element)
        else : L3.append(element)
    L1.sort()
    L1.append(L2).append(L3)
    return L1

推荐阅读