问题
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.
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?
回答1:
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.
Example:
>>> 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)]
回答2:
Shame on Python 3. This was a perfectly well understood concept. That None sorts before any other value.
A = [1,2,3,None];
B = list(sorted(A))
B = [None,1,2,3];
The obsession with strong typing is creeping me out. If we wanted Java or C# we would have used it. This tendency of python to converge to their large surface area of language features is a step in the wrong direction.
To answer the question, and be able to sort properly, massive inefficiencies must be introduced to create "inflated tuples".
A = [(1,2,3,None)]
is now mapped to the hideosity of
A = [(1,1), (1,2), (1,3), (0,None)]
Then sorted, then unpacked.
Is there really someone out there that thinks this kind of overhead and extra code will result in less bugs out there, as opposed to agreeing to the convention that None < 0.
The asylum is being run by the inmates.
The SQL language got NULL wrong (simple expressions like 5 == NULL evaluate to neither True nor False, but NULL) and I was proud of Python that they got it right. 5 == None is obviously False. But now with this sorting botchery, it seems they have got it wrong too.
来源:https://stackoverflow.com/questions/30976124/sort-when-values-are-none-or-empty-strings-python