我需要按特定值對字典列表進行排序。不幸的是,有些值爲None,排序在Python 3中不起作用,因爲它不支持比較None和非None值。我還需要保留None值,並將它們作爲最低值放入新的排序列表中。如何在對排序列表進行排序時使用operator.itemgetter忽略無值?
代碼:
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什麼:
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):
[{'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處理這個特殊的用例:
A number smaller than negative infinity in python?
Is everything greater than None?
Comparing None with built-in types using arithmetic operators?
我可以重新創建的Python 2的在Python 3排序行爲當沒有涉及字典。但我不認爲有辦法與運營商合作。
'回報-float( 'INF')如果NB再無別nb'會表達更短的方式'加權()'。 :-) – BlackJack