python 在什么情况下应该在python中使用内置的'operator'模块?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/467920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In what situation should the built-in 'operator' module be used in python?
提问by Bjorn
I'm speaking of this module: http://docs.python.org/library/operator.html
我说的是这个模块:http: //docs.python.org/library/operator.html
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.
运算符模块导出一组用 C 实现的函数,对应于 Python 的内部运算符。例如,operator.add(x, y) 等价于表达式 x+y。函数名称是用于特殊类方法的名称;为方便起见,还提供了没有前导和尾随 __ 的变体。
I'm not sure I understand the benefit or purpose of this module.
我不确定我是否理解这个模块的好处或目的。
采纳答案by John Fouhy
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))
可能最流行的用法是 operator.itemgetter。给定一个lst
元组列表,您可以按以下方式按第 i 个元素排序: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.
至于其余部分,python 允许使用函数式编程风格,因此它可以出现——例如,Greg 的 reduce 示例。
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
当我可以做的时候,为什么我需要:add = lambda x, y: x+y
?” 答案是:
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, whilelambda
is not. This means that the function can be saved to disk or passed between processes.
operator.add
是(我认为)稍微快一点。- 它使您或以后查看它的其他人更容易理解代码。他们不需要查找 add 的定义,因为他们知道 operator 模块的作用。
operator.add
是可腌制的,而lambda
不是。这意味着该函数可以保存到磁盘或在进程之间传递。
回答by Greg Hewgill
One example is in the use of the reduce()
function:
一个例子是reduce()
函数的使用:
>>> import operator
>>> a = [2, 3, 4, 5]
>>> reduce(lambda x, y: x + y, a)
14
>>> reduce(operator.add, a)
14
回答by Jayhello
for example get column in list whose member is tuple, sort sequence by column:
例如获取成员为元组的列表中的列,按列排序:
def item_ope():
s = ['h', 'e', 'l', 'l', 'o']
print operator.getitem(s, 1)
# e
print operator.itemgetter(1, 4)(s)
# ('e', 'o')
inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
get_count = operator.itemgetter(1)
print map(get_count, inventory)
# [3, 2, 5, 1]
print sorted(inventory, key=get_count)
# [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
see a more practical example, we want to sort a dict by key or value:
看一个更实际的例子,我们想按键或值对字典进行排序:
def dict_sort_by_value():
dic_num = {'first': 11, 'second': 2, 'third': 33, 'Fourth': 4}
# print all the keys
print dic_num.keys()
# ['second', 'Fourth', 'third', 'first']
# sorted by value
sorted_val = sorted(dic_num.items(), key=operator.itemgetter(1))
# [('second', 2), ('Fourth', 4), ('first', 11), ('third', 33)]
print sorted_val
# sorted by key
sorted_key = sorted(dic_num.items(), key=operator.itemgetter(0))
print sorted_key
# [('Fourth', 4), ('first', 11), ('second', 2), ('third', 33)]
another example when we want get the max value and it's index in list:
另一个示例,当我们想要获取最大值及其在列表中的索引时:
def get_max_val_idx():
lst = [1, 7, 3, 5, 6]
max_val = max(lst)
print max_val
# 7
max_idx = lst.index(max_val)
print max_idx
# 1
# simplify it by use operator
index, value = max(enumerate(lst), key=operator.itemgetter(1))
print index, value
# 1 7
More demos like below:
更多演示如下:
import operator
def cmp_fun():
a, b = 5, 3
print operator.le(a, b)
# False
print operator.gt(a, b)
# True
def lst_ope():
lst = [1, 2, 3]
print operator.indexOf(lst, 2)
# 1
lst1 = [1, 2, 3, 2]
print operator.countOf(lst1, 2)
# 2
def cal_ope():
lst1 = [0, 1, 2, 3]
lst2 = [10, 20, 30, 40]
print map(operator.mul, lst1, lst2)
# [0, 20, 60, 120]
print sum(map(operator.mul, lst1, lst2))
# 200
a, b = 1, 3
print operator.iadd(a, b)
# 4
see more from python doc
从python 文档中查看更多信息
回答by eaglebrain
The module is useful when you need to pass a function as an argument to something. There are then two options: use the operator
module, or define a new function (using def
or lambda
). If you define a function on the fly, this can create a problem if you need to pickle this function, either to save it to disk or to pass it between processes. While itemgetter
is picklable, dynamically defined functions (either with def
or lambda
) are not. In the following example, replacing itemgetter
with a lambda
expression will result in a PicklingError
.
当您需要将函数作为参数传递给某物时,该模块很有用。然后有两个选项:使用operator
模块,或定义一个新函数(使用def
或lambda
)。如果您动态定义一个函数,那么如果您需要腌制该函数以将其保存到磁盘或在进程之间传递它,则会产生问题。虽然itemgetter
是可腌制的,但动态定义的函数(withdef
或lambda
)不是。在以下示例中,替换itemgetter
与lambda
表达将导致PicklingError
。
from operator import itemgetter
def sort_by_key(sequence, key):
return sorted(sequence, key=key)
if __name__ == "__main__":
from multiprocessing import Pool
items = [([(1,2),(4,1)], itemgetter(1)),
([(5,3),(2,7)], itemgetter(0))]
with Pool(5) as p:
result = p.starmap(sort_by_key, items)
print(result)
回答by Steve Wehba
In general, the purpose of this module (as alluded to by some of the answers, above) is to provide you with canned functions for simple operations you would otherwise have to write yourself and pass to higher-order function such as sort()
or reduce()
.
一般来说,这个模块的目的(正如上面的一些答案所暗示的那样)是为您提供简单操作的罐头函数,否则您必须自己编写并传递给高阶函数,例如sort()
or reduce()
。
For example, without operators, to sum the numbers in a list, you would have to do something like this:
例如,如果没有运算符,要对列表中的数字求和,您必须执行以下操作:
from functools import reduce
l = list(range(100))
f = lambda x, y: x + y
result = reduce(f, l)
print(result)
With the operator module, you could make use of its add()
function like this:
使用 operator 模块,您可以add()
像这样使用它的功能:
from operator import add
result = reduce(add, l)
print(result)
Thus avoiding the need to create a lambda expression.
从而避免了创建 lambda 表达式的需要。