2017-08-17 88 views
0

我需要按特定值對字典列表進行排序。不幸的是,有些值爲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排序行爲當沒有涉及字典。但我不認爲有辦法與運營商合作。

回答

2

我找到了一種通過在值上使用lambda鍵來實現它的方法。這是代碼:

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 

有可能是另一種方式來寫的「加權」功能短,但它的工作原理。這個想法只是返回-infinite for None值,然後按值排序。

我希望它能幫助,

+2

'回報-float( 'INF')如果NB再無別nb'會表達更短的方式'加權()'。 :-) – BlackJack