程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python3 tutorial: operator module

編輯:Python

Operator—— Standard functional operator interface .

When using iterators in code , Sometimes you have to create a function for a simple expression . In some cases, these functions can use a lambda Function implementation , But for some operations , There's no need to write a new function . therefore operator The module defines some functions , These functions correspond to arithmetic 、 Compare with other and standard objects API Corresponding operation .

1. Logical operators (Logical Operations)

The following function determines the Boolean equivalent value of a value , Or negating it creates the opposite Boolean value , Or compare objects to determine whether they are the same .

from operator import *
a = -1
b = 5
print('a =', a)
print('b =', b)
print()
print('not_(a) :', not_(a))
print('truth(a) :', truth(a))
print('is_(a, b) :', is_(a, b))
print('is_not(a, b):', is_not(a, b))

not_() There is an underline after , Because not yes Python keyword .true() The logic and if Statement adds an expression or converts an expression to bool.is_() Same logic when .is_() The implementation is to use is Check with the same keyword ,is_not() The same check is performed, but the opposite result is returned .

a = -1
b = 5
not_(a) : False
truth(a) : True
is_(a, b) : False
is_not(a, b): True

2. Comparison operator (Comparison Operators)

It supports all rich comparison operators :

from operator import *
a = 1
b = 5.0
print('a =', a)
print('b =', b)
for func in (lt, le, eq, ne, ge, gt):
print('{}(a, b): {}'.format(func.__name__, func(a, b)))

These functions are equivalent to using <、<=、==、>= and > The expression syntax of .

a = 1
b = 5.0
lt(a, b): True
le(a, b): True
eq(a, b): False
ne(a, b): True
ge(a, b): False
gt(a, b): False

3. arithmetic operator (Arithmetic Operators)

It also supports arithmetic operators for manipulating numeric values :

from operator import *
a = -1
b = 5.0
c = 2
d = 6
print('a =', a)
print('b =', b)
print('c =', c)
print('d =', d)
print('\n Positive numbers / negative :')
print('abs(a):', abs(a))
print('neg(a):', neg(a))
print('neg(b):', neg(b))
print('pos(a):', pos(a))
print('pos(b):', pos(b))
print('\n The arithmetic :')
print('add(a, b) :', add(a, b))
print('floordiv(a, b):', floordiv(a, b))
print('floordiv(d, c):', floordiv(d, c))
print('mod(a, b) :', mod(a, b))
print('mul(a, b) :', mul(a, b))
print('pow(c, d) :', pow(c, d))
print('sub(b, a) :', sub(b, a))
print('truediv(a, b) :', truediv(a, b))
print('truediv(d, c) :', truediv(d, c))
print('\n Bitwise :')
print('and_(c, d) :', and_(c, d))
print('invert(c) :', invert(c))
print('lshift(c, d):', lshift(c, d))
print('or_(c, d) :', or_(c, d))
print('rshift(d, c):', rshift(d, c))
print('xor(c, d) :', xor(c, d))

There are two kinds of division operators :floordiv()( stay 3.0 Before the release Python Integer division implemented in ) and truediv()( Floating point division ).

a = -1
b = 5.0
c = 2
d = 6
Positive numbers / negative :
abs(a): 1
neg(a): 1
neg(b): -5.0
pos(a): -1
pos(b): 5.0
The arithmetic :
add(a, b) : 4.0
floordiv(a, b): -1.0
floordiv(d, c): 3
mod(a, b) : 4.0
mul(a, b) : -5.0
pow(c, d) : 64
sub(b, a) : 6.0
truediv(a, b) : -0.2
truediv(d, c) : 3.0
Bitwise :
and_(c, d) : 2
invert(c) : -3
lshift(c, d): 128
or_(c, d) : 6
rshift(d, c): 1
xor(c, d) : 4

4. Sequence operators (Sequence Operators)

There are four types of operators that deal with sequences : Build sequence 、 Search terms 、 Access content and remove entries from the sequence :

from operator import *
a = [1, 2, 3]
b = ['a', 'b', 'c']
print('a =', a)
print('b =', b)
print('\n Build sequence :')
print(' concat(a, b):', concat(a, b))
print('\n Search for :')
print(' contains(a, 1) :', contains(a, 1))
print(' contains(b, "d"):', contains(b, "d"))
print(' countOf(a, 1) :', countOf(a, 1))
print(' countOf(b, "d") :', countOf(b, "d"))
print(' indexOf(a, 5) :', indexOf(a, 1))
print('\n visit :')
print(' getitem(b, 1) :',
getitem(b, 1))
print(' getitem(b, slice(1, 3)) :',
getitem(b, slice(1, 3)))
print(' setitem(b, 1, "d") :', end=' ')
setitem(b, 1, "d")
print(b)
print(' setitem(a, slice(1, 3), [4, 5]):', end=' ')
setitem(a, slice(1, 3), [4, 5])
print(a)
print('\n Delete :')
print(' delitem(b, 1) :', end=' ')
delitem(b, 1)
print(b)
print(' delitem(a, slice(1, 3)):', end=' ')
delitem(a, slice(1, 3))
print(a)

Some of these operations , Such as setitem() and delitem(), Modifying a sequence is an in place operation , No return value .

a = [1, 2, 3]
b = ['a', 'b', 'c']
Build sequence :
concat(a, b): [1, 2, 3, 'a', 'b', 'c']
Search for :
contains(a, 1) : True
contains(b, "d"): False
countOf(a, 1) : 1
countOf(b, "d") : 0
indexOf(a, 5) : 0
visit :
getitem(b, 1) : b
getitem(b, slice(1, 3)) : ['b', 'c']
setitem(b, 1, "d") : ['a', 'd', 'c']
setitem(a, slice(1, 3), [4, 5]): [1, 4, 5]
Delete :
delitem(b, 1) : ['a', 'c']
delitem(a, slice(1, 3)): [1]

5. In place operator (In-place Operators)

In addition to the standard operators , Many object types also support special operators ( Such as +=)" In situ " modify . The in place operator has the same function :

from operator import *
a = -1
b = 5.0
c = [1, 2, 3]
d = ['a', 'b', 'c']
print('a =', a)
print('b =', b)
print('c =', c)
print('d =', d)
print()
iadd(a, b)
print('a = iadd(a, b) =>', a)
print()
iconcat(c, d)
print('c = iconcat(c, d) =>', c)

The above example demonstrates only individual functions . For more information , Refer to the standard library documentation .

a = -1
b = 5.0
c = [1, 2, 3]
d = ['a', 'b', 'c']
a = iadd(a, b) => -1
c = iconcat(c, d) => [1, 2, 3, 'a', 'b', 'c']

6. Attributes and content "Getters"

operator One of the most outstanding features of the module is getter The concept of . These are callable objects constructed at run time , Used to retrieve object properties or contents from a sequence .getter Especially useful when dealing with iterators or generator sequences , Because their cost is less than lambda and Python function .

from operator import *
class MyObj:
"""attrgetter Demo class """
def __init__(self, arg):
super().__init__()
self.arg = arg
def __repr__(self):
return 'MyObj({})'.format(self.arg)
l = [MyObj(i) for i in range(5)]
print('objects :', l)
# Extract... From each object 'arg' attribute 
g = attrgetter('arg')
vals = [g(i) for i in l]
print('arg values:', vals)
# Use arg Sort 
l.reverse()
print('reversed :', l)
print('sorted :', sorted(l, key=g))

Properties in this example getters Function like :lambda x, n=‘attrname’: getattr(x, n):

objects : [MyObj(0), MyObj(1), MyObj(2), MyObj(3), MyObj(4)]
arg values: [0, 1, 2, 3, 4]
reversed : [MyObj(4), MyObj(3), MyObj(2), MyObj(1), MyObj(0)]
sorted : [MyObj(0), MyObj(1), MyObj(2), MyObj(3), MyObj(4)]

And the content getters Function like lambda x, y=5: x[y]:

''' No one answers the problems encountered in learning ? Xiaobian created a Python Exchange of learning QQ Group :711312441 Looking for small partners who share the same aspiration , Help each other , There are also good video tutorials and PDF e-book ! '''
from operator import *
l = [dict(val=-1 * i) for i in range(4)]
print('Dictionaries:')
print(' original:', l)
g = itemgetter('val')
vals = [g(i) for i in l]
print(' values:', vals)
print(' sorted:', sorted(l, key=g))
print()
l = [(i, i * -2) for i in range(4)]
print('\nTuples:')
print(' original:', l)
g = itemgetter(1)
vals = [g(i) for i in l]
print(' values:', vals)
print(' sorted:', sorted(l, key=g))

Content getters You can use a dictionary , You can also process sequences .

Dictionaries:
original: [{
'val': 0}, {
'val': -1}, {
'val': -2}, {
'val': -3}]
values: [0, -1, -2, -3]
sorted: [{
'val': -3}, {
'val': -2}, {
'val': -1}, {
'val': 0}]
Tuples:
original: [(0, 0), (1, -2), (2, -4), (3, -6)]
values: [0, -2, -4, -6]
sorted: [(3, -6), (2, -4), (1, -2), (0, 0)]

7. Custom class

operator The function operation in the module is through the standard Python Interface work , Therefore, they can also handle user-defined classes and built-in types .

from operator import *
class MyObj:
""" Examples of overloaded operators """
def __init__(self, val):
super(MyObj, self).__init__()
self.val = val
def __str__(self):
return 'MyObj({})'.format(self.val)
def __lt__(self, other):
""" Less than comparison """
print('Testing {} < {}'.format(self, other))
return self.val < other.val
def __add__(self, other):
"""add operation """
print('Adding {} + {}'.format(self, other))
return MyObj(self.val + other.val)
a = MyObj(1)
b = MyObj(2)
print(' Comparison operation :')
print(lt(a, b))
print('\n Arithmetic operations :')
print(add(a, b))

Comparison operation :

Testing MyObj(1) < MyObj(2)
True

Arithmetic operations :

Adding MyObj(1) + MyObj(2)
MyObj(3)

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved