Operator¶
尹奉
2023年7月5日 12:11:55
Python 标准库 operator 提供了itemgetter
和attrgetter
。
f = attrgetter('name')
的语义同f = lambda b: b.name
,f(b)
会返回b.name
。还支持f = attrgetter('name.first', 'name.last')
,这时f(b)
会返回(b.name.first, b.name.last)
。itemgetter
同理,不过b.name
要换成b['name']
。
排序、查找可能用到这些东西。
from collections import namedtuple
from operator import attrgetter
from bisect import bisect
Movie = namedtuple('Movie', ('name', 'released', 'director'))
movies = [
Movie('Jaws', 1975, 'Spielberg'),
Movie('Titanic', 1997, 'Cameron'),
Movie('The Birds', 1963, 'Hitchcock'),
Movie('Aliens', 1986, 'Cameron')
]
by_year = attrgetter('released')
movies.sort(key=by_year)
# Find the first movie released after 1960
movies[bisect(movies, 1960, key=by_year)]
operator.attrgetter(attr)
- operator — Standard operators as functions — Python 3.11.4 documentation
Examples - bisect — Array bisection algorithm — Python 3.11.4 documentation