当值是None或空字符串时排序python [英] Sort when values are None or empty strings python

查看:283
本文介绍了当值是None或空字符串时排序python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有字典的列表,在其中按不同的值对它们进行排序.我正在使用以下代码行:

I have a list with dictionaries in which I sort them on different values. I'm doing it with these lines of code:

def orderBy(self, col, dir, objlist):
    if dir == 'asc':
        sorted_objects = sorted(objlist, key=lambda k: k[col])
    else:
        sorted_objects = sorted(objlist, key=lambda k: k[col], reverse=True)
    return sorted_objects

现在的问题是,当我尝试排序时,偶尔会出现空值或空字符串,然后一切都崩溃了.

Now the problem is that I occasionally have null values or empty strings when I try to sort and then it all breaks down.

我不确定,但是我认为这是引发的异常:不可排序的类型:NoneType()< NoneType().当我尝试排序的列上没有None值时,就会发生这种情况.对于空字符串值,尽管它们在列表中排在最后,但它可以工作,但我希望它们排在最后.

I'm not sure but i think that this is the exception that's thrown: unorderable types: NoneType() < NoneType(). It occurs when there is None values on the column I'm trying to sort. For empty string values it works although they end up first in the list but I would like them to be last.

我该如何解决这个问题?

How can I solve this problem?

推荐答案

如果希望None''值最后出现,则可以让key函数返回一个元组,以便对列表进行排序通过该元组的自然顺序.元组的形式为(is_none, is_empty, value);这样,None值的元组将为(1, 0, None)''的元组为(0, 1, ''),而其他任何元素(0, 0, "anything else").因此,这将首先对适当的字符串进行排序,然后对空字符串进行排序,最后对None进行排序.

If you want the None and '' values to appear last, you can have your key function return a tuple, so the list is sorted by the natural order of that tuple. The tuple has the form (is_none, is_empty, value); this way, the tuple for a None value will be (1, 0, None), for '' is (0, 1, '') and for anything else (0, 0, "anything else"). Thus, this will sort proper strings first, then empty strings, and finally None.

示例:

>>> list_with_none = [(1,"foo"), (2,"bar"), (3,""), (4,None), (5,"blub")]
>>> col = 1
>>> sorted(list_with_none, key=lambda k: (k[col] is None, k[col] == "", k[col])) 
[(2, 'bar'), (5, 'blub'), (1, 'foo'), (3, ''), (4, None)]

这篇关于当值是None或空字符串时排序python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆