Built-in functions
Anonymous function
Definition: function without a name
Construction of an anonymous function:
Anonymous functions can only build a simple function, function word
func = lambda x,y: x+y print(func(1,2)) # 3
Anonymous function is most commonly used in conjunction with the built-in functions
# 写匿名函数:接收一个可切片的数据,返回索引为 0与2的对应的元素(元组形式)。 func = lambda li : (li[0],li[2]) print(func([1,2,3])) # (1, 3)
# 写匿名函数:接收两个int参数,将较大的数据返回。 func = lambda x,y: x if x>y else y print(func(2,3)) # 3
Ⅰ built-in function (learn)
eval exce
# eval 剥去字符串的外衣,返回里面的本质 s1 = "{1: 'alex'}" ret = eval(s1) print(ret,type(ret)) # {1: 'alex'} <class 'dict'> ######## s2 = '1 + 3' print(eval(s2)) # 4 ######## s3 = input('>>>') #输入1+2 print(eval(s3)) #
# exec 代码流,过程。 s3 = ''' for i in range(3): print(i) ''' exec(s3) # 0 1 2
hash: Get an object (the object may be a hash: int, str, Bool, tuple) hash value.
print(hash(123214134)) #123214134 print(hash('fkljdsaklgjdfs')) #6499605431360755377
help: function module or function for viewing purposes described in detail.
callable: function is used to check whether an object is callable. If it returns True, object may still call fails; but if it returns False, the calling object ojbect will never succeed.
name = 'alex' def func(): pass print(callable(name)) # False print(callable(func)) # True
int: function is used to convert a string or an integer number.
print(int()) # 0 print(int('12')) # 12 print(int(3.6)) # 3 print(int('0100',base=2)) # 将2进制的 0100 转化成十进制。结果为 4
float: function is used to convert the integer to floating point and string.
complex: a function to create the complex value real + imag * j or transformed string or a plural number. If the first parameter is a string, there is no need to specify the second parameter.
print(complex(1,2)) # (1+2j)
bin: to convert decimal to binary and back.
print(bin(10),type(bin(10))) # 0b1010 <class 'str'>
oct: converted to decimal octal string and returns.
print(oct(10),type(oct(10))) # 0o12 <class 'str'>
hex: decimal converted to a hexadecimal string and returns.
print(hex(10),type(hex(10))) # 0xa <class 'str'>
divmod: the divisor and the dividend calculation result, returns a tuple of the quotient and remainder of (a // b, a% b).
print(divmod(7,2)) # (3, 1)
round: retention of floating-point decimal places, default retention integer.
print(round(7/3,2)) # 2.33 print(round(7/3)) # 2
pow: find x ** y power. (Three parameters of x to the power of y result modulo z)
print(pow(2,3)) # 两个参数为2**3次幂 print(pow(2,3,3)) # 三个参数为2**3次幂,对3取余。
bytes: for conversion between different coding.
s = '你好' bs = bytes(s,encoding='utf-8') print(bs)
ord: Enter the characters to find the position of the character encoding
print(ord('a')) # 97 print(ord('中')) # 20013
chr: Enter the numbers to find out the location of the corresponding character
print(ord(97)) # 'a' print(ord(20013)) # '中'
repr: Returns a string form of the object (true colors).
# %r 原封不动的写出来 # name = 'taibai' # print('我叫%r'%name) # 我叫'taibai' # repr 原形毕露 print(repr('{"name":"alex"}')) # '{"name":"alex"}' print('{"name":"alex"}') # {"name":"alex"}
all: iterables in all True is True
print(all([1,2,True,0])) # False
any: iterables, there is a True True
print(any([1,'',0])) # Ture
Built-in functions Ⅱ (focus)
print () screen output.
print(111,222,333,sep='*') # 111*222*333 print(111,end='') print(222) #两行的结果 111222 f = open('log','w',encoding='utf-8') print('写入文件',fle=f,flush=True)
int()、str()、bool()、set()、tuple()
list () will be converted into a list iterable
l1 = list('abcd') print(l1) # ['a', 'b', 'c', 'd']
dict () to create a dictionary corresponding way.
li = ['盖伦', '德邦', '皇子', '剑圣'] print({i:li[i] for i in range(len(li))}) # {0: '盖伦', 1: '德邦', 2: '皇子', 3: '剑圣'}
abs () returns the absolute value of
i = -5 print(abs(i)) # 5
sum () sums
print(sum([1,2,3])) # 6 print(sum((1,2,3),100)) # 106 100为起始值
min () for the minimum
print(min([1,2,3])) # 返回此序列最小值 ret = min([1,2,-5,],key=abs) # 按照绝对值的大小,返回此序列最小值 print(ret) # 加key是可以加函数名,min自动会获取传入函数中的参数的每个元素,然后通过你设定的返回值比较大小,返回最小的传入的那个参数。 print(min(1,2,-5,6,-3,key=lambda x:abs(x))) # 可以设置很多参数比较大小
dic = {'a':3,'b':2,'c':1} # 将dic值最小的键返回。 # 将dic值最小的值返回。 print(min(dic,key=lambda x:dic[x])) # c x为dic的key,lambda的返回值(即dic的值进行比较)返回最小的值对应的键 print(dic[min(dic,key=lambda x:dic[x])]) # 1 对键取值
dic = {'a':['铁憨憨',67],'b':['碎小梦', 95],'c':['逆小寒', 85]} # 将成绩最低的从属于的那个列表返回。 # 将成绩最低的分数返回。 print(dic[min(dic,key=lambda x:dic[x][1])]) # ['铁憨憨', 67] print(dic[min(dic,key=lambda x:dic[x][1])][1]) # 67
max () use the same maximum and minimum values.
the reversed () will be a sequence of flip flip sequence returns an iterator
l = reversed('你好') # l 获取到的是一个生成器 print(l) # <reversed object at 0x00000147D4178780> print(list(l)) # ['好', '你']
zip () method of the slide fastener. Iteration function for the object as a parameter to be the corresponding element of the object packed into a tuple,
Then return the contents of these tuples composition, if the number of elements of each iterator inconsistent, according to the length of the shortest return,
li = [1,2,3,4] s = 'hjk' dic = {1:'德玛',2:'盖伦',3:'草丛伦'} for i in zip(li,s,dic): print(i) #以元素个数最小的为准,字典返回的是键 # (1, 'h', 1) # (2, 'j', 2) # (3, 'k', 3)
sorted sort function
语法:sorted(iterable,key=None,reverse=False)
li = [12,43,23,56,13] print(sorted(li)) # [12, 13, 23, 43, 56] print(sorted(li,reverse=True)) # [56, 43, 23, 13, 12]
# 对字典使用返回的是排序后的key dic = {'信手斩龙':99,'赝品':80,'奥里奥':90,'残雪':98} print(sorted(dic,key=lambda x:dic[x])) # ['赝品', '奥里奥', '残雪', '信手斩龙']
# 按照列表中每一项的分数排序 l1 = [{'id':'信手斩龙','评分':99}, {'id':'奥里奥','评分':90}, {'id':'赝品','评分':80}, {'id':'残雪','评分':98}] print(sorted(l1,key=lambda x:x['评分'])) # [{'id': '赝品', '评分': 80}, {'id': '奥里奥', '评分': 90}, {'id': '残雪', '评分': 98}, {'id': '信手斩龙', '评分': 99}]
filter filtering filtering, the filter is similar to the pattern generator
Syntax: filter (function, iterable)
function: function for screening, the filter will automatically transfer the iterable the elements to function, according to the function then returns
Back True or False to determine whether to keep this data
# 筛选出评分在90以下的 l1 = [{'id':'信手斩龙','评分':99}, {'id':'奥里奥','评分':90}, {'id':'赝品','评分':80}, {'id':'残雪','评分':98}] print(filter(lambda x: x['评分'] > 90,l1)) # <filter object at 0x000001F8531F9A20> 直接用filter()产生的是一个迭代器 print(list(filter(lambda x: x['评分'] > 90,l1))) # 通过list()对其进行取值 # [{'id': '信手斩龙', '评分': 99}, {'id': '残雪', '评分': 98}]
map mapping function
Syntax: map (function, iterable) can enter iterables mapping in each element were performed taking function
# 计算列表中每个元素的平方,返回新列表 lst = [1,2,3,4,5] print(map(lambda x:x**2,lst)) # <map object at 0x000001E17B879828> print(list(map(lambda x:x**2,lst))) #[1, 4, 9, 16, 25]
reduce
First action is to reduce the list of two elements taken before a value is calculated and then the temporarily stored, followed by the calculated value and temporarily stored in the third list element, obtaining a new value of the most start overwrite values stored temporarily, and then calculated using this new value and the fourth in the list of temporary elements. and so on.
from functools import reduce l = reduce(lambda x,y:x+y,[1,2,3,4]) print(l) # 10 li = reduce(lambda x,y:x+y,['ab','c']) print(li) # abc