排序的关键论点如何工作? [英] How does the key argument to sorted work?

查看:61
本文介绍了排序的关键论点如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码1:

>>> sorted("This is a test string from Andrew".split(), key=str.lower)
    ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']

代码2:

>>> student_tuples = [
...     ('john', 'A', 15),
...     ('jane', 'B', 12),
...     ('dave', 'B', 10),
... ]
>>> from operator import itemgetter, attrgetter
>>>
>>> sorted(student_tuples, key=itemgetter(2))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

为什么在代码1中,在 key = str.lower 中省略了(),并且如果包含括号,则会报告错误,但是在中的代码2中会报告错误key = itemgetter(2),是否保留了括号?

Why in code 1, is () omitted in key=str.lower, and it reports error if parentheses are included, but in code 2 in key=itemgetter(2), the parentheses are kept?

推荐答案

The key argument to sorted expects a function, which sorted then applies to each item of the thing to be sorted. The results of key(item) are compared to each other, instead of each original item, during the sorting process.

您可以想象它的工作原理如下:

You can imagine it working a bit like this:

def sorted(thing_to_sort, key):
    #
    # ... lots of complicated stuff ...
    #
            if key(x) < key(y):
                # do something
            else:
                # do something else
    #
    # ... lots more complicated stuff ...
    #
    return result

如您所见,括号()被添加到函数 key inside sorted 中,应用分别为 thing_to_sort 的项 x y .

As you can see, the parentheses () are added to the function key inside sorted, applying it to x and y, which are items of thing_to_sort.

在您的第一个示例中, str.lower 是应用于每个 x y 的函数.

In your first example, str.lower is the function that gets applied to each x and y.

itemmetter 是有点不同.它是一个返回另一个函数的函数,在您的示例中,另一个函数 被应用于 x y .

itemgetter is a bit different. It's a function which returns another function, and in your example, it's that other function which gets applied to x and y.

您可以在控制台中查看 itemgetter 的工作方式:

You can see how itemgetter works in the console:

>>> from operator import itemgetter
>>> item = ('john', 'A', 15)
>>> func = itemgetter(2)
>>> func(item)
15

首先要弄清楚高阶"函数(接受或返回其他函数的函数)可能有点困难,但是它们对许多不同的任务非常有用,因此值得尝试直到它们完成你感觉舒服.

It can be a little hard to get your head around "higher order" functions (ones which accept or return other functions) at first, but they're very useful for lots of different tasks, so it's worth experimenting with them until you feel comfortable.

这篇关于排序的关键论点如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆