A brief introduction to Python built-in functions

Python built-in functions

Python provides 68 built-in functions, which are divided into three parts according to whether they are commonly used:

learn all() any() bytes() callable() chr() complex() divmod() eval() exec() format() frozenset() globals() hash() help() id() input() int() iter() locals() next() oct() ord() pow() repr() round()
focus abs() enumerate() filter() map() max() min() open() range() print() len() list() dict() str() float() reversed() set() sorted() sum() tuple() type() zip() dir()
later stage classmethod() delattr() getattr() hasattr() issubclass() isinstance() object() property() setattr() staticmethod() super()

1. Understand the part

  • eval(): Peel off the outer layer of the string and calculate the code inside. Not recommended for use

​ Especially when str and input are transmitted over the network, eval() must not be used for SQL injection, etc. Because the converted string is easily modified and exploited, eval() directly runs the content inside.

s1='1+2'
print(eval(s1))
>>>3

和eval()相似的另一个函数exec()用于代码流(多行代码),也不建议使用,高危。

  • hash(): Gets the hash value of an object. Hashable objects are immutable objects.
  • help(): Print how to get this object .
  • callable(): Determine whether an object is callable. If True is returned, object may still fail to be called; but if False is returned, calling object object will never succeed.
  • bin(): Convert decimal to binary and return. ★★
    oct(): Convert decimal to octal string and return. ★★
    hex(): Convert decimal to hexadecimal string and return. ★★
print(bin(10),type(bin(10)))  # 0b1010 <class 'str'>
print(oct(10),type(oct(10)))  # 0o12 <class 'str'>
print(hex(10),type(hex(10)))  # 0xa <class 'str'>
  • divmod(): Calculate the result of the divisor and dividend, and return a tuple containing the quotient and remainder (a // b, a % b) round():
    Retain the number of decimal places of the floating point number, and retain the integer by default.
    pow(): Find xy power. (The result of the three parameters xy is the remainder of z)
print(divmod(7,2))  	# (3, 1)
print(round(7/3,2))  	# 2.33
print(round(7/3))  		# 2
print(round(3.32567,3))  # 3.326
print(pow(2,3))  		# 两个参数为2**3次幂
print(pow(2,3,3))  		# 三个参数为2**3次幂,对3取余。
  • bytes(): used for conversion between different encodings.
s = '你好'						
bs = s.encode('utf-8')
print(bs)						# b'\xe4\xbd\xa0\xe5\xa5\xbd'
s1 = bs.decode('utf-8')
print(s1)						# 你好
bs = bytes(s,encoding='utf-8')
print(bs)						# b'\xe4\xbd\xa0\xe5\xa5\xbd'
b = '你好'.encode('gbk')
b1 = b.decode('gbk')
print(b1.encode('utf-8'))		# b'\xe4\xbd\xa0\xe5\xa5\xbd'
  • ord: Enter the character to find the position of the character encoding. You can check the Ascii code or Unicode.
    chr: Enter the position number to find the corresponding character.
# ord 输入字符找该字符编码的位置
print(ord('a'))		# 97
print(ord('中'))		# 20013

# chr 输入位置数字找出其对应的字符
print(chr(97))		# a
print(chr(20013))	# 中
  • repr(): Returns the string form of an object (revealing its original shape) ★★★ Often used in object-oriented
print(repr('{"name":"alex"}'))		# '{"name":"alex"}'
print('{"name":"alex"}')			# {"name":"Alex"}
  • In formatted output, %r also has the function of repr() function:
s1 = '中国人'
msg = '我是%r' % s1
print(msg) 				# 我是'中国人'
  • all(): In an iterable object, it is True if all are True
    any(): In an iterable object, if there is one True, it is True
print(all([1,2,True,0]))		# False
print(any([1,'',0]))			# True

3. Master the key points

  • int(): The function is used to convert a string or number into an integer, which can be used for rounding.
    float: Function used to convert integers and strings to floating point numbers.
    complex: The function is used to create a complex number with the value real + imag * j or to convert a string or number into a complex number. If the first parameter is a string, there is no need to specify the second parameter.
  • print(): screen output function
    • 格式:print(self, args, sep=’ ‘, end=’\n’, file=None)
    • args: Positional parameters, no content limit.
      sep=' ': The interval between output multiple elements defaults to one space.
print('a',3,5,11,'kv',sep='|')		# a|3|5|11|kv
    • end='\n': The end of a call defaults to a newline character
  • list(): Convert an iterable object into a list
list1=list('amwkvi')
print(list1)			# ['a', 'm', 'w', 'k', 'v', 'I']
  • tuple(): Convert an iterable object into a tuple
  • dict(): Create a dictionary in the corresponding way
dict1 = dict([('one', 1), ('two', 2),('three', 3)])
dict2 = dict(one=1, two=2, three=3)
dict3 = dict({
    
    'one': 1, 'two': 2, 'three': 3})
dict4 = {
    
    'one': 1, 'two': 2, 'three': 3}
dict5 = dict.fromkeys('abc',[1,2,3])
  • abs(): Returns the absolute value of a number. ★★★
    sum(): Sum, find the sum of iterable objects (numeric type). ★★★
l1 = [i for i in range(10)]
print(sum(l1))			# 45
print(sum(l1,100))		# 设置初始值100,就是在100的基础上进行做sum,结果为:145
  • reversed(): reverses a sequence and returns an iterator of the reversed sequence
l1=list('amwkvi')
print(l1)				# ['a', 'm', 'w', 'k', 'v', 'i']
l2=list(reversed(l1))	# l2变量得到的是一个翻转的迭代器,所以需要用list函数进行转化
print(l2)				# ['i', 'v', 'k', 'w', 'm', 'a']
  • zip(): zip method, which combines several iterable objects into a generator in order. The length of the generator content depends on the shortest of these objects. ★★★
l1 = [1, 2, 3, 4, 5]
tu1 = ('a', 'b', 'c')			# tu1最短,以该对象为准,一一对应产生一个生成器
s1 = 'kill'
obj = zip(l1, tu1, s1)
# for i in obj:
#     print(i)
print(list(obj))				# [(1, 'a', 'k'), (2, 'b', 'i'), (3, 'c', 'l')]
>>>(1, 'a', 'k')
(2, 'b', 'i')
(3, 'c', 'l')
  • min(): Find the minimum value. ★★★★★
    Format: min(*args, key=None)
    • Example 1: Output the minimum absolute value in the l1 list, and the subsequent key processes the absolute value of each element.
l1 = [1, 2, 3, 4, 5, -9, 19, -16]
print(min(l1,key=abs))				# 1
    • Example 2: Find the key-value pair with the smallest value
dic = {
    
    'a': 3, 'b': 2, 'c': 1}
# print(min(dic))	 	# min默认会按照字典的键去比较大小,所以得出是a。
# def dic_value(k):		# 手动建立一个函数,输入键,返回值
#     return dic[k]
# print(min(dic,key=dic_value))	# 输出的是值最小的键

print(dic[min(dic,key=lambda k:dic[k])]) # 写成一行代码,使用匿名函数,传入键,返回值,min函数通过lambda对每个值进行比较大小。
    • Example 3: Find the name of the youngest person in the list
l2 = [('太白', 18), ('alex', 73), ('wusir', 35), ('口天吴', 41)]
print(min(l2, key=lambda k: k[1])[0])		# 太白
# k变量中每次传入的是列表中的每个元组,返回值为元组中的第二项,然后交给min函数进行比较。
# min的比较结果是一个元组,最后再取元组中的第一个元素,即人的名字。
  • max(): Find the maximum value. ★★★★★
    格式:max(*args, key=None)
    Any function that can add a key: it will automatically pass each element in the iterable pair into the function corresponding to the key in order, and compare the size with the return value.
  • sorted(): A sorting function that sorts an iterable object and returns a new list. By default, the order is sorted from low to high, and the reverse=True parameter can be used to reverse the order.
    格式:sorted(*args, **kwargs)
l2 = [('太白', 18), ('alex', 73), ('wusir', 35), ('口天吴', 41)]
# 默认按照列表中每个元素的第一个内容进行排序。
print(sorted(l2))  # [('alex', 73), ('wusir', 35), ('口天吴', 41), ('太白', 18)]
# 加上key之后,使用匿名函数指定按照第二个内容进行排序。
print(sorted(l2, key=lambda x: x[1]))  
# [('太白', 18), ('wusir', 35), ('口天吴', 41), ('alex', 73)]
print(sorted(l2,key=lambda x:x[1],reverse=True))
# 加上reverse=True之后,将逆序排序。
# [('alex', 73), ('口天吴', 41), ('wusir', 35), ('太白', 18)]
  • filter(): Filter, filter, similar to list comprehension filtering mode. The difference between this function and the list comprehension is that the return value is an iterator.
    • Example: list comprehension and filter() demonstration
list1 = [2, 4, 11, 9, 5, 8]
# 列表推导式实现输出大于6的内容:[11, 9, 8]
print([i for i in list1 if i > 6])		# 返回的是个列表
# 使用filter()函数实现该功能:[11, 9, 8]
print(list(filter(lambda x: x > 6, list1)))	# 返回的是个迭代器,需要用list进行转换。
  • map() function: a loop (traversal) mode similar to list comprehension. The difference between it and list comprehension is that the return value is an iterator.
    • Example: List comprehension and map() demonstration, the program needs to produce a regular list: [1, 4, 9, 16,25]
# 使用列表推导式生成列表:[1, 4, 9, 16 ,25]
print([i * i for i in range(1, 6)])
# 使用map函数进行生成列表:[1, 4, 9, 16 ,25]
obj = map(lambda i: i * i, range(1, 6))
# obj 为迭代器,想要得到列表需要用list方法实现
print(list(obj))
  • reduce() function: This function is not a built-in function and needs to be imported externally.
    Function:
    第一步:先把列表中的前俩个元素取出,按function规则计算出一个值'a',然后临时保存着;
    第二步:将这个临时保存的值'a'和列表中第三个元素传入至function进行计算,再求出一个新的值'b';
    第三步:又将这个新的值'b'覆盖掉'a',读取列表中第四个元素传入至function进行计算。以此类推。(个人理解类似 “i++”)
    Format: reduce(function, sequence, initial=None)
    In the Python2.x version, recover can be imported directly. In the Python3.x version, it needs to be imported from the functools package.
    Example:
from functools import reduce
list1 = [3, 5, 8, 2, 9, 7]

# 方法一:使用自定义函数实现将列表中所有元素进行相加
def func1(a, b):
    return a + b
print(reduce(func1, list1))		# 34

# 方法二:使用lambda实现将列表中所有数字变成一个整数
print(reduce(lambda a, b: a * 10 + b, list1))		# 358297

Picture sharing

Insert image description here

Guess you like

Origin blog.csdn.net/Jo_Francis/article/details/126121408