Python common functions or libraries

range()

range(start, stop[, step])
Description: Returns an iterator (not a list, but an iterator) whose start value is start, end value is stop, and value interval is step

Parameter description:
start: counting starts from start. The start parameter can not be passed, and the default is to start from 0 and
stop: counting to the end of stop, but not including stop.
step: step size, the default is 1.

data = range(3, 15, 2)
for i in data:
    print(i, end='\t')

"""
运行结果:
3	5	7	9	11	13	
"""

Math library

Math: The built-in mathematical function library provided by python contains many mathematical formulas

numeric constant

constant mathematical representation describe
math.pi Pi Pi, with a value of 3.14159…
math.e e Natural logarithm with a value of 2.7182818…
math.inf positive infinity, negative infinity is -math.inf
math.nan IN Not a Number, Not a Number
>>> import math
>>> math.pi
3.141592653589793
>>> math.e
2.718281828459045
>>> math.inf
inf
>>> -math.inf
-inf
>>> math.nan
nan

Number Theory and Representation Functions

function describe with
ceil(x) Rounded up
floor(x) round down
factorial(x) factorial
gcd(a, b) greatest common divisor
fab(x) absolute value
>>> import math
>>> math.ceil(3.14)
4
>>> math.ceil(-3.14)
-3
>>> math.ceil(3)
3
>>> math.floor(3.14)
3
>>> math.floor(-3.14)
-4
>>> math.floor(3)
3
>>> math.factorial(3)
6
>>> math.factorial(4)
24
>>> math.gcd(64, 96)
32
>>> math.fabs(-4.67)
4.67
>>> math.fabs(4.68)
4.68

power logarithmic function

function describe with
pow(x, y) Returns x raised to the power of y
exp(x) e (natural logarithm) to the power of x
sqrt(x) square root of x
log(x, base=math.e) Returns the logarithm of x
>>> import math
>>> math.pow(2, 4)
16.0
>>> math.pow(4, 0.5)
2.0
>>> math.exp(5)
148.4131591025766
>>> math.exp(2)
7.38905609893065
>>> math.sqrt(4)
2.0
>>> math.sqrt(25)
5.0
>>> math.log(7.38905609893065)
2.0

Conversion

method describe
bin(num) Convert the decimal value num to binary (num must be of type int)
eight Convert the decimal value num to octal (num must be int type)
int(num, base=10) Convert to decimal according to the specified base (note that if the parameter base is passed, num must be in the form of a string
hex(num) Convert the decimal value num to hexadecimal (num must be int type)
>>> bin(4)
'0b100'
>>> type(bin(4))
<class 'str'>
>>> bin("5")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an integer

>>> oct(12)
'0o14'
>>> type(oct(12))
<class 'str'>
>>> oct("12")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an integer

>>> int(34.6)
34
>>> int("101", 2)
5
>>> int("0o12", 8)
10
>>> int("34.2", 10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '34.2'
>>> int("34", 10)
34
>>> int("1b", 16)
27
>>> int(101, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: int() can't convert non-string with explicit base
>>> type(int("101", 2))
<class 'int'>

>>> hex(20)
'0x14'
>>> type(hex(20))
<class 'str'>
>>> hex("20")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an integer
>>>

zip()

zip is a built-in function of python, which packs the elements in the iterable object into tuples, and the tuples form a list and return

Method: zip([iterable, ...])
[iterable, ...] is a list composed of iterators, iterable means iterators
If the number of elements of each iterator is inconsistent, the length of the returned list is the same as the shortest object, use the * operator operator to unpack a tuple into a list.
Unzip: zip(*zip object)

>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = [4, 5, 6, 7, 8]

# zip()函数将多个迭代器从同一个位置的元素组成元组,返回zip对象
>>> d1 = zip(a, b)
>>> print(d1)
<zip object at 0x000002228D8ECBC0>
>>> type(d1)
<class 'zip'>
# zip对象可以通过list()转成列表对象
>>> data1 = list(d1)
>>> data1
[(1, 4), (2, 5), (3, 6)]

# 迭代器的元素个数不一致时,则打包到元素个数最少的那一个
>>> list(zip(a, b, c))
[(1, 4, 4), (2, 5, 5), (3, 6, 6)]

# zip(*zip对象),如果zip对象未被解包过,则可以通过该格式进行解包,如果已经解包过,则返回空列表
>>> d2 = zip(a, b)
>>> d3 = zip(*d2)
>>> d3
<zip object at 0x000002228D8ECDC0>
>>> list(d3)
[(1, 2, 3), (4, 5, 6)]
>>> list(d3)
[]

map()

Format: map(function, iterable, …)
The function parameter is a function, and iterable is a sequence object
Return value: After processing the elements in the sequence object according to the function function, the returned map object (python3)
can be passed through list(), tuple( ) and other operations to convert the map object into the specified data type
Note: as many required parameters as the function pointed to by function, then there must be as many parameters as iterable

def square(x):
    return x ** 2

m = map(square, [1, 2, 3, 4, 5])
print(f"map()返回的值是:{
      
      m},其类型是:{
      
      type(m)}")

print(f"map对象第一次被遍历:{
      
      list(m)}\n第2次从第1次结束位置开始遍历(所以为空):{
      
      list(m)}")

print(f"元组:{
      
      tuple(map(square, [1, 2, 3, 4, 5]))}")
print(f"集合:{
      
      set(map(square, [1, 2, 3, 4, 5]))}")


def add(x, y):
    return x + y
print(f"函数有多个必传参数:{
      
      list(map(add, [1, 2, 3, 4, 5], [6, 7, 8, 9, 10]))}")

# 按照指定的进制转换为十进制数
print("使用python自带的函数", list(map(int, ["2", "21", "2a"], [10, 8, 16])))

print("使用了lambda关键字:", list(map(lambda x: 2*x, [3, 7, 1, 6])))

The execution results are as follows:

map()返回的值是:<map object at 0x000001F3AEDE7460>,其类型是:<class 'map'>
map对象第一次被遍历:[1, 4, 9, 16, 25]
第2次从第1次结束位置开始遍历(所以为空):[]
元组:(1, 4, 9, 16, 25)
集合:{1, 4, 9, 16, 25}
函数有多个必传参数:[7, 9, 11, 13, 15]
使用python自带的函数 [2, 17, 42]
使用了lambda关键字: [6, 14, 2, 12]

eval()

Format: eval(expression[, globals[, locals]])

  • source: execution statement expression (string format), required
  • globals: optional parameter, global namespace, passed in as a dictionary
  • locals: optional parameter, local namespace, when setting locals, must have globals
    description: convert source into an executable statement and execute it.
    Note: The source involves variables, functions, and methods. The search order is: locals --> globals. If neither of the two has passed parameters, it will be searched directly from the current module (that is, if globals or locals are either from the incoming parameters Find, or find from the current module, not compatible)

s = "1+2*3"
result = eval(s)
print(f"eval(s)传入的第一个参数,其值为{
      
      s},类型为{
      
      type(s)},返回结果是{
      
      result},结果的数据类型是{
      
      type(result)}")


x = 21
print(f"eval的表达式中包含变量:{
      
      eval('x - 11')}")

def add(x, y):
    return x+y
print(f'eval的表达式中包含本地函数:{
      
      eval("add(x, 2)")}')


name = "hello"
eval("print(f'无globals参数无locals参数:{name}')")
eval("print(f'有globals参数无locals参数:{name}')", {
    
    "name": "wenxiaoba"})
eval("print(f'无globals参数有locals参数:{name}')", {
    
    "name": "wenxiaoba_global"}, {
    
    "name": "wenxiaoba_local"})

The execution result is:

eval(s)传入的第一个参数,其值为1+2*3,类型为<class 'str'>,返回结果是7,结果的数据类型是<class 'int'>
eval的表达式中包含变量:10
eval的表达式中包含本地函数:23
无globals参数无locals参数:hello
有globals参数无locals参数:wenxiaoba
无globals参数有locals参数:wenxiaoba_local

The following code execution will report an error, because there are globals parameters, so the functions and variables in the first parameter will not be searched in the local module, but globals does not define the add() method (although add() is defined locally), so it will report error

def add(x, y):
    return x+y
print(f'eval的表达式中包含本地函数和globals变量,:{
      
      eval("add(x, 2)", {
      
      "x": 23})}')

The error message is:

Traceback (most recent call last):
  File "D:\hogwart\demo.py", line 22, in <module>
    print(f'eval的表达式中包含本地函数和globals变量,:{eval("add(x, 2)", {"x": 23})}')
  File "<string>", line 1, in <module>
NameError: name 'add' is not defined

Class attribute related functions

method illustrate
hasattr(object, name) Determine whether the object object contains the specified attribute (the attribute name is name)
getattr(object, name[, default]) Returns the value of the attribute named name of the object object
setattr(object, name, value) Set properties for the object object (named name, value value)

harvesttr()

Format: hasattr(object, name)

  • object: An object generated according to a class, also called an instance
  • name: attribute name (can be understood as a variable name in the instance), string type
    Description: Determine whether an object contains a certain attribute, if there is a corresponding attribute, return True, otherwise return False
class Person:
    name = ""
    age = 0

    def is_gender_exit(self):
        # 判断对象中是否包含gender属性
        return hasattr(self, "gender")

p = Person()
print(hasattr(p, 'name'))
print(hasattr(p, 'age'))
print("-----------------------")
print(hasattr(p, 'gender'))
print(p.is_gender_exit())
p.gender = "女"
print(hasattr(p, 'gender'))
print(p.is_gender_exit())

The execution result is:

True
True
-----------------------
False
False
True
True

getattr()

Format: getattr(object, name[, default])

  • object: An object generated according to a class, also called an instance
  • name: attribute name (can be understood as a variable name in the instance), string type
  • default: The default return value. If there is no corresponding attribute in the object, the parameter value will be returned by default. If the parameter is not set and there is no corresponding attribute in the object, an AttributeError error will be triggered. Description: Return the value of the corresponding attribute in the object. If the object has no specified attribute: default is
    passed Returns the default value, and triggers AttributeError when the default parameter is not passed
class Person:
    name = "wenxiaoba"
    age = 18

    def get_name(self):
        return getattr(self, "name")

p = Person()
age = getattr(p, "age", 12)
print(f"年龄age值为:{
      
      age}")
a2 = p.get_name()
print(f"姓名name值为:{
      
      a2}")

gender = getattr(p, "gender", "女")
print(f"性别gender为:{
      
      gender}")

# 对象没有对应的属性,getattr也没有设置default参数,所以会报错
gender = getattr(p, "gender")
print(f"性别gender为:{
      
      gender}")

The execution result is:

年龄age值为:18
姓名name值为:wenxiaoba
性别gender为:女
Traceback (most recent call last):
  File "D:\hogwart\demo.py", line 18, in <module>
    gender = getattr(p, "gender")
AttributeError: 'Person' object has no attribute 'gender'

setattr()

Format: setattr(object, name, value)

  • object: An object generated according to a class, also called an instance
  • name: attribute name (can be understood as a variable name in the instance), string type
  • value: attribute value, that is, the value to be set for the attribute
    Description: set the attribute value for the object
class Person:
    name = "wenxiaoba"
    age = 18

    def set_name(self):
        setattr(self, "name", "harry")

p = Person()
p.set_name()
print(f"使用了对象的set_name()修改名称为:{
      
      p.name}")

setattr(p, "gender", "男")
print(f"使用了setattr()添加了gender属性:gender={
      
      p.gender}")

The execution result is:

使用了对象的set_name()修改名称为:harry
使用了setattr()添加了gender属性:gender=男

enumerate()

enumerate(sequence, start=0)

  • sequence: serialized objects, such as List, Tuple, etc.
    -start: the value of the starting position of the subscript, which starts from 0 by default and
    combines a traversable data object (such as a list, tuple, or string) into an index sequence, and at the same time List the data and data subscripts, that is, list the elements composed of each parameter in the sequence and its subscript + start
data = ["red", "blue", "yellow", "black"]
result = enumerate(data)
print(result)
print(type(result))
print(list(result))
r2 = enumerate(data, 2)
print(list(r2))

The execution result is:

<enumerate object at 0x000001DC38682F80>
<class 'enumerate'>
[(0, 'red'), (1, 'blue'), (2, 'yellow'), (3, 'black')]
[(2, 'red'), (3, 'blue'), (4, 'yellow'), (5, 'black')]

random

Random is also a library that comes with python that is occasionally used. This library has several frequently used methods, specifically in this blog: python common library random

filter()

filter(function_or_None, iterable): Process the elements of the iterable sequence with function_or_None. If the return is not false (false means None, False, empty list, etc.), it means that the element meets the requirements, and the returned data type is filter (iterator), which can be traversed

  • function_or_None: the name of the function, when None is passed, it means that the sequence will not be filtered
  • iterable: sequence
def is_even(num):
    # 判断是否为偶数,为偶数时返回True
    if int(num)%2 == 0:
        return 2
    return False

data = [2, 3, 4, 5, 6, -4, -7]
r = filter(is_even, data)
print("filter()返回的数据类型为:", type(r))
print("filter(is_even, data)的遍历结果为:", list(r))

print("filter()中使用lambda:", list(filter(lambda x: not x%2, data)))

print("filter()中传入迭代器:", list(filter(lambda x: not x%2, range(10))))

The execution result is:

filter()返回的数据类型为: <class 'filter'>
filter(is_even, data)的遍历结果为: [2, 4, 6, -4]
filter()中使用lambda: [2, 4, 6, -4]
filter()中传入迭代器: [0, 2, 4, 6, 8]

Guess you like

Origin blog.csdn.net/wenxiaoba/article/details/120463130