jay*_*y a 3 python dictionary list python-2.7
例如,如果字典正在{0:0, 1:0, 2:0}
制作一个列表:[0, 0, 0]
.
如果这是不可能的,你如何取字典的最小值,意思是字典:{0:3, 1:2, 2:1}
返回1
?
将字典转换为列表非常简单,您有 3 种口味.keys()
,.values()
并且.items()
>>> test = {1:30,2:20,3:10}
>>> test.keys() # you get the same result with list(test)
[1, 2, 3]
>>> test.values()
[30, 20, 10]
>>> test.items()
[(1, 30), (2, 20), (3, 10)]
>>>
Run Code Online (Sandbox Code Playgroud)
(在python 3中,您需要在这些上调用列表)
>>> min(test.keys()) # is the same as min(test)
1
>>> min(test.values())
10
>>> min(test.items())
(1, 30)
>>> max(test.keys()) # is the same as max(test)
3
>>> max(test.values())
30
>>> max(test.items())
(3, 10)
>>>
Run Code Online (Sandbox Code Playgroud)
(在 python 2 中,为了提高效率,请改用.iter*版本)
最有趣的是找到最小值/最大值的键,最小值/最大值也得到了那个覆盖
>>> max(test.items(),key=lambda x: x[-1])
(1, 30)
>>> min(test.items(),key=lambda x: x[-1])
(3, 10)
>>>
Run Code Online (Sandbox Code Playgroud)
在这里你需要一个关键函数,它是一个函数,它接受你给主函数的任何一个并返回你希望比较它们的元素(你也可以将它转换为其他元素)。
>>> def last(x):
return x[-1]
>>> min(test.items(),key=last)
(3, 10)
>>>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
12049 次 |
最近记录: |