即時通訊使用Python 3.3.1(新手)在Python,字典排序按值,但只能返回鍵
我有一個整數鍵和整數值 字典我需要梳理本字典,並返回一個列表其中值低於閾值鍵的(說「T」)
到目前爲止,我
list_integer = sorted(dict_int_int.items(), key=lambda x: x[1] )
這個排序按值字典 - 一切都很好,到目前爲止,但我怎麼限制值低於't',然後只返回鍵
由於提前
即時通訊使用Python 3.3.1(新手)在Python,字典排序按值,但只能返回鍵
我有一個整數鍵和整數值 字典我需要梳理本字典,並返回一個列表其中值低於閾值鍵的(說「T」)
到目前爲止,我
list_integer = sorted(dict_int_int.items(), key=lambda x: x[1] )
這個排序按值字典 - 一切都很好,到目前爲止,但我怎麼限制值低於't',然後只返回鍵
由於提前
試試這個:
[key for key,value in sorted(dic.items() ,key=lambda x : x[1]) if value < threshold]
或使用operator.itemgetter
:
>>> from operator import itemgetter
>>> [key for key,value in sorted(dic.items() ,key= itemgetter(1)) if value < threshold]
這是正確的答案。早些時候我犯了一個錯誤。但這個答案只返回鍵。尼斯。謝謝 – 2013-05-03 19:00:04
試試這個
list_integer = filter(lambda x: x[1] < t, dict_int_int.items()))
list_integer = sorted([x[0] for x in list_integer])
我只是檢查了這段代碼,並且它返回了所有的字典排序。結果與我跑的 – 2013-05-03 18:36:57
沒有什麼不同。他希望這個值是下面的「t」,但是上面的。另外,你錯過了排序部分。 – abarnert 2013-05-03 18:38:37
已經檢查過,仍然沒有工作 – 2013-05-03 18:40:36
讓我們先從你有什麼:
list_integer = sorted(dict_int_int.items(), key=lambda x: x[1])
這給出了一個按值排序的鍵值對列表(它使名稱有點誤導)。
現在讓我們limit the values to be below 't'
:
list_small = ((k, v) for k, v in list_integer if v < t)
(你也可以寫爲filter
如果你喜歡。)
現在,讓我們ONLY return the keys
:
list_keys = [k for k, v in list_small]
當然,你可以結合這些步驟中的任何兩個,或者甚至將所有三個步驟結合在一起(在這種情況下,最終會得到Ashwini Chaudhary的答案)。
讓我們通過這些一步一步,以確保他們的工作:
>>> dict_int_int = {'a': 1.0, 'b': 0.5, 'c': 0.25, 'd': 0.10 }
>>> t = 0.75
>>> list_integer = sorted(dict_int_int.items(), key=lambda x: x[1])
>>> list_integer
[('d', 0.1), ('c', 0.25), ('b', 0.5), ('a', 1.0)]
>>> list_small = [(k, v) for k, v in list_integer if v < t]
>>> list_small
[('d', 0.1), ('c', 0.25), ('b', 0.5)]
>>> list_keys = [k for k, v in list_small]
>>> list_keys
['d', 'c', 'b']
(請注意,我改變了發電機表達list_small
到一個列表理解這是因爲我們需要打印出其值,然後再次使用它們。發生器表達式只允許您使用其值。)
請不要在您的問題中添加標語。 – Droogans 2013-05-03 18:31:01
請在您的問題中提供樣本輸入和預期輸出。 – abarnert 2013-05-03 18:49:52
abarnert,我不明白你的意思是不把樣本的輸入和預期的輸出 – 2013-05-03 18:56:57