【Python3】operator模块:使用mul, itemgetter, attrgetter, methodcaller等运算符

本文探讨了Python中operator模块的功能,包括高效地执行算术运算,使用itemgetter进行序列和映射的排序,利用attrgetter处理命名元组属性,以及通过methodcaller调用对象方法。这些技巧对于提升代码效率和可读性至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The operator module exports a set of efficient functions corresponding to the intrinsic operators of Python

1. mul

# 使用reduce韩式和一个匿名函数计算阶乘
from functools import reduce
def fact(n):
	return reduce(lambda a, b: a*b, range(1,n+1)

operator模块为多个算术运算符提供了对应的函数, 避免匿名函数

# 使用reduce和operator.mul函数计算阶乘
from functools import reduce
from operator import mul
def fact(n):
	return reduce(mul, range(1, n+1))

2.itemgetter

metro_data=[
	('Tokyo', 'JP', 36.933, (35.689722, 139.691667)),
    ('Delhi NCR', 'IN', 21.935, (28.613889, 77.208889)),
    ('Mexico City', 'MX', 20.142, (19.433333, -99.133333)),
    ('New York-Newark', 'US', 20.104, (40.808611, -74.020386)),
    ('Sao Paulo', 'BR', 19.649, (-23.547778, -46.635833)),
]

from operator import itemgetter
sorted(metro_data, key=itemgetter(1))
结果:
 [
	('Sao Paulo', 'BR', 19.649, (-23.547778, -46.635833)), 
	('Delhi NCR', 'IN', 21.935, (28.613889, 77.208889)), 
	('Tokyo', 'JP', 36.933, (35.689722, 139.691667)), 
	('Mexico City', 'MX', 20.142, (19.433333, -99.133333)),
	('New York-Newark', 'US', 20.104, (40.808611, -74.020386))
]
# itemgetter使用[]运算符,因此支持序列,映射和任何实现了__getitem__方法的类
sorted(metro_data, key=itemgetter(1)) 比较的是metro_data[i][1]. 其中i是metro_data的索引。也就是排序比较的是‘JP’那一列对应的值

3. attrgetter

from collections import namdtuple
LatLong=namedtuple('LatLong', 'lat long')
Metropolis = namedtuple('Metropolis', 'name cc pop coord')
metro_areas = [Metropolis(name, cc, pop, LatLong(lat, long)) for name, cc, pop, (lat, long) in metro_data]

from operator import attrgetter
sorted(metro_areas, key=attrgetter('coord.lat)

# 结果
[
	Metropolis(name='Sao Paulo', cc='BR', pop=19.649, coord=LatLong(lat=-23.547778, long=-46.635833)), 
	Metropolis(name='Mexico City', cc='MX', pop=20.142, coord=LatLong(lat=19.433333, long=-99.133333)), 
	Metropolis(name='Delhi NCR', cc='IN', pop=21.935, coord=LatLong(lat=28.613889, long=77.208889)), 
	Metropolis(name='Tokyo', cc='JP', pop=36.933, coord=LatLong(lat=35.689722, long=139.691667)), 
	Metropolis(name='New York-Newark', cc='US', pop=20.104, coord=LatLong(lat=40.808611, long=-74.020386))
]

# attrgetter使用符号".", 属性运算符。所以sorted(metro_areas, key=attrgetter('coord.lat)比较的是metro_areas[i].coord.lat对象。

4. methodcaller

>>> from operator import methodcaller
>>> s = 'The time has come'
>>> upcase = methodcaller('upper')
>>> upcase(s)
'THE TIME HAS COME'
>>> hiphenate = methodcaller('replace', ' ', '-')
>>> hiphenate(s)
'The-time-has-come'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值