我有一个这样的列表:
list = [
{'price': 2, 'amount': 34},
{'price': 7, 'amount': 123},
{'price': 5, 'amount': 495}
]
如何在 python 中获取具有特定键的最小值/最大值的对象? 有了这个我可以获得最小值:
min(obj['price'] for obj in list) # 2
但是我想要得到的是一个完整的对象
{'price': 2, 'amount':34}
我怎样才能做到这一点?有没有不用 foreach 等的简单方法?
最佳答案
为你的 min
函数使用一个 key
:
from operator import itemgetter
min(my_list, key=itemgetter('price'))
也不要使用 python 的内置关键字和/或数据结构名称作为变量和对象名称。它会通过隐藏内置名称来混淆解释器。
关于python - 如何在 python 中获取特定键的对象最小值/最大值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42013365/