gpt4 book ai didi

python - 如何将字典转换为列表?

转载 作者:行者123 更新时间:2023-11-28 22:30:52 25 4
gpt4 key购买 nike

例如,如果字典是 {0:0, 1:0, 2:0} 则创建一个列表:[0, 0, 0]

如果这不可能,您如何获取字典的最小值,即字典:{0:3, 1:2, 2:1} 返回 1?

最佳答案

转换 dictionary列表非常简单,你有 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)]
>>>

(在 python 3 中你需要调用 list )

使用 min 也可以轻松找到最大值或最小值或 max功能

>>> 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)
>>>

(在 python 2 中,为了提高效率,请改用 .iter* 版本)

最有趣的是找到最小值/最大值的键,最小值/最大值也得到了覆盖

>>> max(test.items(),key=lambda x: x[-1])
(1, 30)
>>> min(test.items(),key=lambda x: x[-1])
(3, 10)
>>>

这里你需要一个关键函数,它是一个函数,它接受你给主函数的任何一个并返回你希望比较它们的元素(你也可以将它转换成其他东西) .

lambda是一种方式 define anonymous功能,让您无需执行此操作

>>> def last(x):
return x[-1]

>>> min(test.items(),key=last)
(3, 10)
>>>

关于python - 如何将字典转换为列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41915545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com