python notes

Know the sequence:

list2=[{'mm':2},{'mm':2},{'mm':3},{'mm':1},{'mm':5},{'mm':4} ,{'mm':3}] 

1. Sort by the value of element mm in list2
list1=sorted(list2,key=lambda list2: list2['mm'])

print(list1) #[{'mm': 1}, {'mm': 2}, {'mm': 2}, {'mm': 3}, {'mm': 3}, {'mm': 4}, {'mm': 5}]
2. Get the first mm element with a value of 4
for index,i in enumerate(list2):
if i['mm'] == 4:
print(index,i)
break #5 {'mm':4}
3. Output list2[::4] 

[{'mm': 2}, {'mm': 5}]
4. Delete all elements with mm value equal to 2 in list2, and do not reassign list2
n=0 
while n<len(list2):
if list2[n]['mm']==2:
del list2[n]
else:
n+=1

print(list2) #[{'mm': 3}, { 'mm': 1}, {'mm': 5}, {'mm': 4}, {'mm': 3}]

5. Take out the element with the largest mm value in list2, which cannot be sorted
ind = 0
def get_max(n):
for i in range(1,len(n)):
global ind
if list2[i]['mm'] > list2[ind]['mm']:
ind = i
return n[ind]
print(get_max(list2)) #{'mm':5}
 

Explain why

>>> '{:0.2f}'.format(3.135)

'3.13'

>>> '{:0.2f}'.format(3.145)

'3.15'

Errors of computer floating point numbers, involving knowledge points: Fixed Point representation of fixed-point numbers

Fixed-point representation of these two numbers

3.145:3.1450000000000000177635683940

3.135:3.1349999999999997868371792719699442386627197265625

So it's a simple rounding: 3.1349 is obviously rounded by 4, 3.1450 is obviously rounded by 5

 magic method in python

In python, those surrounded by two underscores __ have special meanings, and those that are methods are all magic methods.

The magic of magic methods in python is that you don't need explicit calls, you can make automatic calls. In fact, each magic method is an overriding of the built-in method, and acts like a decorator

  The most commonly used magic methods,

  __init__(self[,...]) __init__ , through which we can define the initial operation of an object. __new__(cls[,...]) __new__ is the first method called when an object is instantiated, the first parameter is the class, other parameters are used to pass directly to the __init__ method, __new_ _Decide whether to use the __init__ method.

magic method
meaning
 
basic magic method
__new__(cls[, ...]) 1. __new__ is the first method called when an object is instantiated
2. Its first parameter is the class, and other parameters are used to pass directly to the __init__ method
3. __new__ decides whether to use the __init__ method, because __new__ can call the constructor of other classes or directly return other instance objects as an instance of this class. If __new__ does not return an instance object, __init__ will not be called
. 4. __new__ is mainly used for inherit from an immutable type such as a tuple or string
__init__(self[, ...]) Constructor, the initialization method called when an instance is created
__del__(self) Destructor, a method called when an instance is destroyed
__call__(self[, args...]) Allows an instance of a class to be called like a function: x(a, b) calls x.__call__(a, b)
__len __ (self) Defines the behavior when called by len()
__repr__(self) Defines the behavior when called by repr()
__str__(self) Defines the behavior when called by str()
__bytes__(self) Defines the behavior when called by bytes()
__hash__(self) Defines the behavior when called by hash()
__bool__(self) Defines the behavior when called by bool(), should return True or False
__format__(self, format_spec) Defines the behavior when format() is called
  related properties
__getattr__(self, name) Defines the behavior when the user tries to get a property that does not exist
__getattribute__(self, name) Defines the behavior when properties of this class are accessed
__setattr__(self, name, value) Defines the behavior when a property is set
__delattr__(self, name) Defines the behavior when an attribute is deleted
__dir __ (self) Defines the behavior when dir() is called
__get__(self, instance, owner) Defines the behavior when the descriptor's value is fetched
__set__(self, instance, value) Defines the behavior when the descriptor's value is changed
__delete__(self, instance) Defines the behavior when the descriptor's value is deleted
  comparison operator
__lt__(self, other) Defines the behavior of the less-than sign: x < y calls x.__lt__(y)
__le__(self, other) Define the behavior of the less-than-equal sign: x <= y call x.__le__(y)
__eq__(self, other) Defines the behavior of the equal sign: x == y calls x.__eq__(y)
__ne__(self, other) Defining the behavior of the inequality sign: x != y calls x.__ne__(y)
__gt__(self, other) Defines the behavior of the greater-than sign: x > y calls x.__gt__(y)
__ge__(self, other) Define the behavior of the greater-than-equal sign: x >= y call x.__ge__(y)
  arithmetic operators
__add__(self, other) Define the behavior of addition: +
__sub__(self, other) Define the behavior of subtraction:-
__mul__(self, other) Define the behavior of multiplication: *
__truediv__(self, other) Define the behavior of true division :/
__floordiv__(self, other) Defines the behavior of integer division: //
__mod__(self, other) Define the behavior of the modulo algorithm: %
__divmod__(self, other) Defines the behavior when called by divmod()
__pow__(self, other[, modulo]) Defines the behavior when called by power() or ** evaluated
__lshift__(self, other) Defines the behavior of bitwise left shift: <<
__rshift__(self, other) Defines the behavior of bitwise right shift: >>
__and__(self, other) Defines the behavior of the bitwise AND operation: &
__xor__(self, other) Defines the behavior of the bitwise XOR operation: ^
__or__(self, other) Define the behavior of the bitwise OR operation: |
  Inverse operation
__radd__(self, other) (same as above, called when the corresponding operation is not supported by the left operand)
__rsub__(self, other) (same as above, called when the corresponding operation is not supported by the left operand)
__rmul__(self, other) (same as above, called when the corresponding operation is not supported by the left operand)
__rtruediv__(self, other) (same as above, called when the corresponding operation is not supported by the left operand)
__rfloordiv__(self, other) (same as above, called when the corresponding operation is not supported by the left operand)
__rmod__(self, other) (same as above, called when the corresponding operation is not supported by the left operand)
__rdivmod__(self, other) (same as above, called when the corresponding operation is not supported by the left operand)
__rpow__(self, other) (same as above, called when the corresponding operation is not supported by the left operand)
__rlshift__(self, other) (same as above, called when the corresponding operation is not supported by the left operand)
__rrshift__(self, other) (same as above, called when the corresponding operation is not supported by the left operand)
__rxor__(self, other) (same as above, called when the corresponding operation is not supported by the left operand)
__ror__(self, other) (与上方相同,当左操作数不支持相应的操作时被调用)
  增量赋值运算
__iadd__(self, other) 定义赋值加法的行为:+=
__isub__(self, other) 定义赋值减法的行为:-=
__imul__(self, other) 定义赋值乘法的行为:*=
__itruediv__(self, other) 定义赋值真除法的行为:/=
__ifloordiv__(self, other) 定义赋值整数除法的行为://=
__imod__(self, other) 定义赋值取模算法的行为:%=
__ipow__(self, other[, modulo]) 定义赋值幂运算的行为:**=
__ilshift__(self, other) 定义赋值按位左移位的行为:<<=
__irshift__(self, other) 定义赋值按位右移位的行为:>>=
__iand__(self, other) 定义赋值按位与操作的行为:&=
__ixor__(self, other) 定义赋值按位异或操作的行为:^=
__ior__(self, other) 定义赋值按位或操作的行为:|=
  一元操作符
__neg__(self) 定义正号的行为:+x
__pos__(self) 定义负号的行为:-x
__abs__(self) 定义当被 abs() 调用时的行为
__invert__(self) 定义按位求反的行为:~x
  类型转换
__complex__(self) 定义当被 complex() 调用时的行为(需要返回恰当的值)
__int__(self) 定义当被 int() 调用时的行为(需要返回恰当的值)
__float__(self) 定义当被 float() 调用时的行为(需要返回恰当的值)
__round__(self[, n]) 定义当被 round() 调用时的行为(需要返回恰当的值)
__index__(self) 1. 当对象是被应用在切片表达式中时,实现整形强制转换
2. 如果你定义了一个可能在切片时用到的定制的数值型,你应该定义 __index__
3. 如果 __index__ 被定义,则 __int__ 也需要被定义,且返回相同的值
  上下文管理(with 语句)
__enter__(self) 1. 定义当使用 with 语句时的初始化行为
2. __enter__ 的返回值被 with 语句的目标或者 as 后的名字绑定
__exit__(self, exc_type, exc_value, traceback) 1. 定义当一个代码块被执行或者终止后上下文管理器应该做什么
2. 一般被用来处理异常,清除工作或者做一些代码块执行完毕之后的日常工作
  容器类型
__len__(self) 定义当被 len() 调用时的行为(返回容器中元素的个数)
__getitem__(self, key) 定义获取容器中指定元素的行为,相当于 self[key]
__setitem__(self, key, value) 定义设置容器中指定元素的行为,相当于 self[key] = value
__delitem__(self, key) 定义删除容器中指定元素的行为,相当于 del self[key]
__iter__(self) 定义当迭代容器中的元素的行为
__reversed__(self) 定义当被 reversed() 调用时的行为
__contains__(self, item) 定义当使用成员测试运算符(in 或 not in)时的行为

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325118151&siteId=291194637