>>> from operator import itemgetter
>>> a = [(5, 3), (1, 3), (1, 2), (2, -1), (4, 9)]
>>> sorted(a, key=itemgetter(0))
[(1, 3), (1, 2), (2, -1), (4, 9), (5, 3)]
Run Code Online (Sandbox Code Playgroud)
这是如何运作的?key 也是一个函数吗?我对 key=itemgetter(0) 背后的内容感到困惑?如果有人可以一步一步解释
itemgetter(..)[python-doc]是构造函数的函数。这个概念在计算机科学中被称为柯里化[wiki]。柯里化在函数式编程语言中非常常见。
itemgetter 的简化版本将实现如下:
def itemgetter(key):
def f(item):
return item[key]
return f
Run Code Online (Sandbox Code Playgroud)
例如,如果我们构造一个itemgetter(1),然后我们可以调用该函数,例如:
>>> f = itemgetter(1)
>>> f([1,4,2,5])
4
Run Code Online (Sandbox Code Playgroud)
所以这里f(..)将采取列表的第二项。
key 也是一个函数吗?
是的,这key是一个函数。正如[python-doc]的文档sorted(..)所述:
key指定一个只有一个参数的函数,用于从 iterable 中的每个元素中提取比较键(例如,key=str.lower)。默认值是None(直接比较元素)。
| 归档时间: |
|
| 查看次数: |
1490 次 |
| 最近记录: |