在对字典列表进行排序时,如何用operator.itemgetter忽略None值? [英] How to ignore None values with operator.itemgetter when sorting a list of dicts?
问题描述
我需要按特定值对词典列表进行排序.不幸的是,有些值是None,并且排序在Python 3中不起作用,因为它不支持将None与not None值进行比较.我还需要保留None值,并将它们作为最低值放在新的排序列表中.
I need to sort a list of dictionaries by a specific value. Unfortunately, some values are None and the sorting does not work in Python 3 because of the fact that it does not support comparison of None with not None values. I need to retain the None values as well and place them as lowest values in the new sorted list.
代码:
import operator
list_of_dicts_with_nones = [
{"value": 1, "other_value": 4},
{"value": 2, "other_value": 3},
{"value": 3, "other_value": 2},
{"value": 4, "other_value": 1},
{"value": None, "other_value": 42},
{"value": None, "other_value": 9001}
]
# sort by first value but put the None values at the end
new_sorted_list = sorted(
(some_dict for some_dict in list_of_dicts_with_nones),
key=operator.itemgetter("value"), reverse=True
)
print(new_sorted_list)
我在Python 3.6.1中得到的东西:
What I get in Python 3.6.1:
Traceback (most recent call last):
File "/home/bilan/PycharmProjects/py3_tests/py_3_sorting.py", line 15, in <module>
key=operator.itemgetter("value"), reverse=True
TypeError: '<' not supported between instances of 'NoneType' and 'NoneType'
我需要什么(这在Python 2.7中有效):
What I need (this works in Python 2.7):
[{'value': 4, 'other_value': 1}, {'value': 3, 'other_value': 2}, {'value': 2, 'other_value': 3}, {'value': 1, 'other_value': 4}, {'value': None, 'other_value': 42}, {'value': None, 'other_value': 10001}]
是的,我知道也有与此类似的问题,但是它们不能通过operator.itemgetter处理这个特定的用例:
Yes, I know there are similar questions to this one, but they do not deal with this particular use case with operator.itemgetter:
当不涉及字典时,我可以在Python 3中重新创建Python 2的排序行为.但是我没有找到与操作员一起执行此操作的方法.
I can recreate the sorting behavior of Python 2 in Python 3 when there are no dictionaries involved. But I don't see a way to do this with the operator.
推荐答案
我找到了一种通过在值上使用lambda键来做到这一点的方法.这是代码:
I found a way to do it by using lambda key on value. This is the code:
L = [ # I mixed them to shown the sorting
{"value": 1, "other_value": 4},
{"value": 2, "other_value": 3},
{"value": None, "other_value": 2},
{"value": 4, "other_value": 1},
{"value": None, "other_value": 42},
{"value": 3, "other_value": 9001}
]
def weighted(nb):
if nb is None:
return -float('inf')
else:
return nb
L.sort(key=lambda x:weighted(x["value"]), reverse=True)
print(L) # => return the expected output in python 3.6
可能还有另一种写短加权"函数的方法,但是它可以工作.这个想法只是为None值返回-infinite,然后按该值排序.
There is probably another way to write the "weighted" function shorter but it works. The idea is just to return -infinite for None value and then sort by the value.
我希望对您有帮助,
这篇关于在对字典列表进行排序时,如何用operator.itemgetter忽略None值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!