[英]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.