即时通讯使用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