![](/img/trans.png)
[英]Fastest and simplest way of getting a list from list in keys of a dictionary
[英]What's the simplest way to get the highest and lowest keys from a dictionary?
self.mood_scale = {
'-30':"Panic",
'-20':'Fear',
'-10':'Concern',
'0':'Normal',
'10':'Satisfaction',
'20':'Happiness',
'30':'Euphoria'}
我需要设置两个变量: max_mood
和min_mood
,所以我可以对自动收报机设置一些限制。 获得最低和最高密钥的最简单方法是什么?
>>> min(self.mood_scale, key=int)
'-30'
>>> max(self.mood_scale, key=int)
'30'
这应该这样做:
max_mood = max(self.mood_scale)
min_mood = min(self.mood_scale)
也许不是最有效的(因为它必须两次获取和遍历键列表),但肯定非常明显和清晰。
更新:我没有意识到你的密钥是字符串。 既然听起来好像这是一个错误,我会让它保持原样,但请注意它需要键才能成为实际的整数。
这是有效的Python吗? 我想你的意思是:
mood_scale = {
'-30':"Panic",
'-20':'Fear',
'-10':'Concern',
'0':'Normal',
'10':'Satisfaction',
'20':'Happiness',
'30':'Euphoria'}
print mood_scale[str(min(map(int,mood_scale)))]
print mood_scale[str(max(map(int,mood_scale)))]
输出
恐慌情绪
使用整数作为键更好更快
mood_scale = {
-30:"Panic",
-20:'Fear',
-10:'Concern',
0:'Normal',
10:'Satisfaction',
20:'Happiness',
30:'Euphoria'}
print mood_scale[min(mood_scale))]
print mood_scale[max(mood_scale))]
编辑2:使用迭代器要快得多
print timeit.timeit( lambda: mood_scale[min(mood_scale.keys())])
print timeit.timeit( lambda: mood_scale[min(mood_scale)])
1.05913901329
0.662925004959
另一种解决方案可能是在插入时跟踪最大/最小值并简单地做一下mood_scale.min()/ max()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.