gpt4 book ai didi

python - Python 最小/最大关键字函数

转载 作者:太空狗 更新时间:2023-10-30 00:54:37 24 4
gpt4 key购买 nike

我想了解这是如何工作的:

my_dict = {'a':2,'b':1}
min(my_dict, key=my_dict.get)

产生

b

这是一个非常酷的功能,我想更好地理解它。
基于documentation

min(iterable[, key]) Return the smallest item in an iterable or the smallest of two or more arguments... The optional key argument specifies a one-argument ordering function like that used for list.sort(). The key argument, if supplied, must be in keyword form (for example, min(a,b,c,key=func)).

在哪里可以找到有关可用功能的更多信息?如果是字典,是不是都是字典方法?

编辑:我今天遇到了这个:

max(enumerate(array_x), key=operator.itemgetter(1))

仍在寻找有关 min/max 的可用关键字函数的信息

最佳答案

你写的代码是

my_dict = {'a':2,'b':1}
min(my_dict, key=my_dict.get)

实际上这适用于 min 函数。那么,min 是做什么的?

min(a, b, c, ...[, key=func]) -> value

With a single iterable argument, return its lowest item. With two or more arguments, return the lowest argument.

这里的key是用来传递自定义比较函数的。

示例:按列表长度输出最大值,其中 arg1、arg2 均为列表。

>>>> max([1,2,3,4], [3,4,5], key=len)
[1, 2, 3, 4]

但是如果我想要列表中的最大值,但要考虑元组的第二个元素怎么办?这里我们可以使用函数,官方给的documentation . def 语句是复合语句,它们不能用在需要表达式的地方,这就是有时使用 lambda 的原因。

请注意,lambda 等同于您在 def 的返回语句中输入的内容。因此,您不能在 lambda 中使用语句,只允许使用表达式。

>>> max(l, key = lambda i : i[1])
(1, 9)

# Or

>>> import operator
>>> max(l, key = operator.itemgetter(1))
(1, 9)

所以函数基本上取决于可迭代对象和传递比较标准。

现在在您的示例中,您正在遍历字典。在 key 中,您在这里使用 get 方法。

The method get() returns a value for the given key. If key is not available then returns default value None.

在这里,get 方法中没有参数,它只是迭代字典的值。因此 min 为您提供具有最小值的 key 。

对于 max(enumerate(array_x), key=operator.itemgetter(1))我们想比较数组的值而不是它们的索引。所以我们枚举了这个数组。

enumerate(thing), where thing is either an iterator or a sequence, returns a iterator that will return (0, thing[0]), (1, thing1), (2, thing[2])

现在我们已经使用了 operator 模块的 itemgetter 函数。 operator.itemgetter(n) 构造一个可调用对象,假定可迭代对象(例如列表、元组、集合)作为输入,并从中获取第 n 个元素。

你也可以像这里一样使用lambda函数

max(enumerate(array_x), key=lambda i: i[1])

所以key中的功能范围差不多就可以使用了。我们可以使用许多功能,但唯一的动机是,它是比较的标准。

关于python - Python 最小/最大关键字函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36502505/

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