python - 在 Python 中使用 sorted()

标签 python

<分区>

Possible Duplicate:
Syntax behind sorted(key=lambda :)

我正在浏览 documentation并遇到了这个例子:

> student_tuples = [
      ('john', 'A', 15),
      ('jane', 'B', 12),
      ('dave', 'B', 10), ]

> sorted(student_tuples, key=lambda student: student[2])  # sort by age 
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

我不明白的是这里的lambda和student是什么?可以用其他名称代替吗? :student:student[2] 中做了什么?这有点模棱两可,因为我以前从未遇到过。

最佳答案

语义上,这:

print sorted(student_tuples, key=lambda student: student[2])

与此相同:

def sort_key(student):
    return student[2]

print sorted(student_tuples, key=sort_key)

lambda 只是为函数定义提供了另一种语法。结果是一个函数对象,就像由 def 创建的对象一样。但是,lambda 函数无法执行某些操作,例如定义新变量。它们非常适合(取决于您询问的对象)创建小型的一次性功能,例如这个。

一旦你明白了这一点,那么你所要做的就是 key 接受一个函数,对传递给 sorted 的序列中的每个值调用它,并对值根据其相应的 key 值自行排序时的顺序排列。

关于python - 在 Python 中使用 sorted(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12791923/

相关文章:

python - 为什么我会收到 "instance has no attribute ' __getitem_ _' "错误?

python - 抓取 : How to fetch an attribute in a <abbr> tag

python - 使用 matplotlib 根据日期更改图形线的颜色

python - Bs4 按类别查找 p 标签

python - 如何将系列或序列分配给 dask 数据框列?

python - 使用 SimpleCV 需要多少 Python 知识?

python - numpy 和 Keras 中 "reshape"函数的差异

python - 更改 matplotlib 轴中的 x 轴刻度标签

python - 有没有办法在 Python 中编写脚本来更改 Linux 中的用户密码?如果是这样,如何?

python - 如何根据模运算在 PyTorch 张量的末尾添加零?