我想对短列表进行排序:
# 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))
但它不起作用
如何排序? (数字值优先,“未找到”的优先级较低,最后是“”)
答案 0 :(得分:1)
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
答案 1 :(得分:1)
编辑:按要求对非数字值进行排序
ar = [i for i in row if not i.isnumeric()]
ar.sort(reverse=True)
row = [i for i in row if i.isnumeric()] + ar
答案 2 :(得分:0)
这将对您的列表进行排序,并使'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('')
答案 3 :(得分:0)
这也可以解决问题:
+
结果:
TimeSpan