python内置模块在哪_在哪种情况下,应在python中使用内置的“ operator”模块?

From the article:

The operator module exports a set of

functions implemented in C

corresponding to the intrinsic

operators of Python. For example,

operator.add(x, y) is equivalent to

the expression x+y. The function names

are those used for special class

methods; variants without leading and

trailing __ are also provided for

convenience.

I'm not sure I understand the benefit or purpose of this module.

解决方案

Possibly the most popular usage is operator.itemgetter. Given a list lst of tuples, you can sort by the ith element by: lst.sort(key=operator.itemgetter(i))

Certainly, you could do the same thing without operator by defining your own key function, but the operator module makes it slightly neater.

As to the rest, python allows a functional style of programming, and so it can come up -- for instance, Greg's reduce example.

You might argue: "Why do I need operator.add when I can just do: add = lambda x, y: x+y?" The answers are:

operator.add is (I think) slightly faster.

It makes the code easier to understand for you, or another person later, looking at it. They don't need to look for the definition of add, because they know what the operator module does.

operator.add is picklable, while lambda is not. This means that the function can be saved to disk or passed between processes.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值