2017-08-17 4 views
0

辞書のリストを特定の値でソートする必要があります。残念ながら、NoneとNoneの値の比較をサポートしていないという理由で、Python 3ではソートが機能しません。 None値も保持し、それらを新しいソートリストに最低値として配置する必要があります。無視する方法dictsのリストをソートするときに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 3でのPython 2の並べ替え動作を再作成することができます。しかし、私はオペレータがこれを行う方法を見ていない。

答えて

2

lambda key on valueを使用する方法が見つかりました。これはコードです:

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 

「加重」関数を短く書くもう1つの方法がありますが、それは機能します。考え方は、None値に対して-infiniteを返し、値でソートすることです。私はそれが役に立てば幸い

+2

'リターン-float NBなし他nb'を表現する短い方法だろうであれば( 'INF')'加重() '。 :-) – BlackJack

関連する問題