簡體   English   中英

PYTHON 用空值、字符串和數值排序列表

[英]PYTHON Sort list with empty, string and numeric values

我想對短列表進行排序,例如:

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

但它不工作

我該如何排序? (數值在前,“未找到”優先級較低,最后是“”)

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

編輯:按要求對非數值進行排序

ar = [i for i in row if not i.isnumeric()]
ar.sort(reverse=True)
row = [i for i in row if i.isnumeric()] + ar

這將對您的列表進行排序並給予'not found'''更高的優先級:

l = [int(a) for a in row if a.isnumeric()] # Or float(a)
l.sort()
row = [str(a) for a in l] +\
    ['not found'] * row.count('not found') +\
    [''] * row.count('')

這也可以解決問題:

row = ['not found', '', 555, 1, '5' , 444]
print(row)

def func(x):
    if str(x).isnumeric():
        return  1/-int(x) # ordering numerics event if they are strings 
    elif str(x) == 'not found':
        return  2
    elif str(x) == '':
        return  3

row2 = row.sort(key=func)

print(row)

結果:

['not found', '', 555, 1, '5', 444]
[1, '5', 444, 555, 'not found', '']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM