在哪种情况下,应在python中使用内置的"operator"模块? [英] In what situation should the built-in 'operator' module be used in python?

查看:130
本文介绍了在哪种情况下,应在python中使用内置的"operator"模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我说的是这个模块: http://docs.python.org/library/operator.html

I'm speaking of this module: http://docs.python.org/library/operator.html

摘自文章:

操作员模块导出一组 用C实现的功能 对应于内在 Python的运算符.例如, operator.add(x,y)等效于 表达式x + y.函数名称 是那些用于特殊班级的人 方法;没有前导和的变体 还提供了尾随__ 方便.

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.

推荐答案

可能最流行的用法是operator.itemgetter.给定一个元组列表lst,您可以按以下方式按ith元素排序:lst.sort(key=operator.itemgetter(i))

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.

关于其余部分,python允许使用一种函数式编程,因此它可以出现-例如,Greg的reduce示例.

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

您可能会争辩:当我可以做的时候,为什么我需要operator.add?"?答案是:

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

  1. operator.add(我认为)要快一点.
  2. 它使您或以后的其他人更容易理解该代码.他们不需要寻找add的定义,因为他们知道操作员模块的作用.
  3. operator.add是可腌制的,而lambda不是.这意味着该功能可以保存到磁盘或在进程之间传递.
  1. operator.add is (I think) slightly faster.
  2. 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.
  3. operator.add is picklable, while lambda is not. This means that the function can be saved to disk or passed between processes.

这篇关于在哪种情况下,应在python中使用内置的"operator"模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆