理解通过字典排序并为超过阈值的一定数量的值返回键
Comprehension on Sorting through a dictionary and returning the key for a certain amount of values above a threshold
我已经弄清楚了我的理解并让它工作以返回排序列表的键。所以我目前正在返回前 X 数量的具有最低值的键。我不太确定如何对此规定值高于阈值。
coin_loss_dict = {'ETH': -1.25,'BTC': -5.92,'ETC': -2.50,'OMG': -0.75}
x = -3.5
main_list = ([i[0] for i in sorted(coin_loss_dict.items(), key=lambda x:x[1], reverse=True)[:2]])
我不确定如何准确地适应它,但我希望它采用高于阈值 (x) 的 2 个值。我已经看到 >= x 在 dict.items() 之后的位置,但这似乎对我不起作用。
main_list = ([i[0] for i in sorted(coin_loss_dict.items() >= x, key=lambda x:x[1], reverse=True)[:2]])
我收到一个很好的错误,告诉我我不能在 dict_items 和 float 的实例之间这样做。
TypeError: '>=' not supported between instances of 'dict_items' and 'float'
如果能得到任何帮助,我将不胜感激。我知道理解并不是最适合使用的,但它可以满足我的需要,但我似乎无法合并的阈值除外。
试试这个:
coin_loss_dict = {'ETH': -1.25,'BTC': -5.92,'ETC': -2.50,'OMG': -0.75}
x = -3.5
main_list = ([i[0] for i in sorted(coin_loss_dict.items(), key=lambda x:x[1], reverse=True) if i[1] >= x])
我已经弄清楚了我的理解并让它工作以返回排序列表的键。所以我目前正在返回前 X 数量的具有最低值的键。我不太确定如何对此规定值高于阈值。
coin_loss_dict = {'ETH': -1.25,'BTC': -5.92,'ETC': -2.50,'OMG': -0.75}
x = -3.5
main_list = ([i[0] for i in sorted(coin_loss_dict.items(), key=lambda x:x[1], reverse=True)[:2]])
我不确定如何准确地适应它,但我希望它采用高于阈值 (x) 的 2 个值。我已经看到 >= x 在 dict.items() 之后的位置,但这似乎对我不起作用。
main_list = ([i[0] for i in sorted(coin_loss_dict.items() >= x, key=lambda x:x[1], reverse=True)[:2]])
我收到一个很好的错误,告诉我我不能在 dict_items 和 float 的实例之间这样做。
TypeError: '>=' not supported between instances of 'dict_items' and 'float'
如果能得到任何帮助,我将不胜感激。我知道理解并不是最适合使用的,但它可以满足我的需要,但我似乎无法合并的阈值除外。
试试这个:
coin_loss_dict = {'ETH': -1.25,'BTC': -5.92,'ETC': -2.50,'OMG': -0.75}
x = -3.5
main_list = ([i[0] for i in sorted(coin_loss_dict.items(), key=lambda x:x[1], reverse=True) if i[1] >= x])