Getting Started with Python Python based tutorial of built-in functions

1, a built-in function

(1) eval (): type of code execution string, and returns a final result artifact

a = "88 + 99"
print(eval(a))

eval("n + 4")  # 85
eval('print(666)')  # 666

Note: Do remember banned

(2) exec (): execution string artifact two types of code

def func():
    print(111)
func()

exec(func())

Note: Do remember banned

(3) hash (): function is to distinguish between variable data types and data types immutable

print(hash("123"))
print(hash(12))
print(hash(-1))
print(hash(-10))
print(hash((2,1)))

dic = {[1,2,3]:2}
print(hash([1,2,3]))

(4) help (): to view help information, see the functions or modules described in detail for purposes

help(list) 

(5) callable (): Check whether the object can be called

def func():
    print(1)
lst = [1,23,4,]
print(callable(lst))

(6) int (): converts a string or an integer number

print(int())  
print(int('12'))  
print(int(3.6))  

(7) float (): converts a string to integer and floating point

print(float(3))
print(int(3))

(8) complex (): plural

print(complex(20))

(9) bin (): turn Decimal Binary 0b

print(bin(100))

(10) oct (): Decimal turn octal 0o

print(oct(10)) 

(11) hex (): Decimal turn hex 0x

print(hex(17))

(12) divmod (): the quotient and the remainder (quotient, remainder)

print(divmod(5,2))

(13) round (): Reserved decimal places

print(round(3.534232,2)) 

(14) pow (): pow exponentiation is when two parameters are exponentiation, when the three parameters are the modulo exponentiation

print(pow(2,2))  #幂 pow 两个参数是求幂
print(pow(2,2,3))  #幂 pow 两个参数是求幂后的余

(15) bytes (): string encoding, for conversion between different coding

s = "你好"
s1 = bytes(s,encoding="utf-8")
print("s1")

(16) ord (): Get the number of the current through the element epitope

print(ord("你"))

(17) chr (): by element lookup table bit number

print(chr(20320))

(18) repr (): ecological view data source, for programmers

a = 'alex'
print(repr(a))   #查看你数据的原生态  -- 给程序员使用的
print(a)         # 给用户使用的

(19) all (): determining whether the container elements are true (and)

lst = [1,2,0,4,5]
print(all(lst)) 

(20) any (): determining whether the container element has a true

lst = [1,2,3,0,1,23]  
print(any(lst))

(21) globals (): see global variables

print(globals()) 

(22) locals (): View the current spatial variables

a = 10
def func():
    a = 1
    print(locals())     #  查看当前空间变量
    print(1)

func()

(23) frozenset (): Freeze collection

2, two built-in functions

(1) Common function:

<1> print () screen output

''' 源码分析
def print(self, *args, sep=' ', end='\n', file=None): # known special case of print
    """
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    file:  默认是输出到屏幕,如果设置为文件句柄,输出到文件
    sep:   打印多个值之间的分隔符,默认为空格
    end:   每一次打印的结尾,默认为换行符
    flush: 立即把内容输出到流文件,不作缓存
    """
'''
sep : 每一个元素之间分割的方法 默认 " "    ****
print(1,2,3,sep="|")

end :print执行完后的结束语句 默认\n        ****
print(1,2,3,end="")
print(4,5,6,end="")

file : 文件句柄 默认是显示到屏幕
print(1,2,3,4,file=open("test","w",encoding="utf-8"))

print()  # flush 刷新
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

<2> dir () to view the current object's method returns a list of all

print(dir(list))  # 查看当前对象所有方法  返回的是列表print(dir(str))  # 查看当前对象所有方法

<3> format () format conversion

# 对齐方式
print(format("alex",">20"))  # 右对齐
print(format("alex","<20"))  # 左对齐
print(format("alex","^20"))  # 居中

# 进制转换
print(format(10,"b"))      # bin  二进制
print(format(10,"08b"))
print(format(10,"08o"))    # oct  八进制
print(format(10,"08x"))    # hex  十六进制
print(format(0b1010,"d"))  # digit 十进制

<4> str () into a string of bytes

byte_str = bytes("你好",encoding="utf")
print(byte_str)
print(str(byte_str,encoding="utf-8"))

<5> list () to an object into a list iteration

print(list("alex"))

<6> tuple () iterator objects can speak into a tuple

print(tuple([1,2,3,4]))

<7> set () will be converted into a set iterables

print(set("alex"))

<8> dict () to create a corresponding way dictionaries

print(dict([(1,2),(3,4)]))

print(dict(k=1,v=2,c=3))

dic1 = {"key1":1,"key2":2}
dic2 = {"a":1,"b":2}
dic2.update(dic1)
print(dic2)

print(dict(**dic1,**dic2))

<9> abs () returns the absolute value

i = -5
print(abs(i))  # 5

<10> sum () summation

print(sum([1,2,3]))
print(sum((1,2,3),100))     # 从100开始加

<11> reversed () will be a sequence of inversion, inversion sequence returns iterator

print(list(reversed("alex")))

lst = [1,2,3,4,5]
print(list(reversed(lst)))  反转
print(lst)

<12> zip () fastener

The iteration may be used as the first parameter of the object corresponding to the elements packed into a tuple, and return the contents of these tuples composition, if the number of elements of each iterator inconsistent, according to the length of the shortest return.

lst1 = [1,2,3]

lst2 = ['a','b','c','d']

lst3 = (11,12,13,14,15)

for i in zip(lst1,lst2,lst3):

    print(i)
    

结果:

(1, 'a', 11)

(2, 'b', 12)

(3, 'c', 13)

(2) order function:

<1> min () for the minimum

rint(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}
print(min(dic,key=lambda x:dic[x]))

# x为dic的key,lambda的返回值(即dic的值进行比较)返回最小的值对应的键

<2> max () selecting the maximum value

print(max(10,12,13,15,16))
print(max([10,12,13,15,-16],key=abs))

<3> sorted () function to sort

语法:sorted(iterable,key=None,reverse=False)

iterable : 可迭代对象

key: 排序规则(排序函数),在sorted内部会将可迭代对象中的每一个元素传递给这个函数的参数.根据函数运算的结果进行排序

reverse :是否是倒序,True 倒序 False 正序

lst = [1,3,2,5,4]
lst2 = sorted(lst)
print(lst)    #原列表不会改变
print(lst2)   #返回的新列表是经过排序的


lst3 = sorted(lst,reverse=True)
print(lst3)   #倒叙

结果:
[1, 3, 2, 5, 4]
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]

字典使用sorted排序

dic = {1:'a',3:'c',2:'b'}
print(sorted(dic))   # 字典排序返回的就是排序后的key

结果:
[1,2,3]




和函数组合使用

# 定义一个列表,然后根据一元素的长度排序
lst = ['天龙八部','西游记','红楼梦','三国演义']

# 计算字符串的长度
def func(s):
    return len(s)
print(sorted(lst,key=func))

# 结果:
# ['西游记', '红楼梦', '天龙八部', '三国演义']


和lambda组合使用

lst = ['天龙八部','西游记','红楼梦','三国演义']

print(sorted(lst,key=lambda s:len(s)))

结果:
['西游记', '红楼梦', '天龙八部', '三国演义']


lst = [{'id':1,'name':'alex','age':18},
    {'id':2,'name':'wusir','age':17},
    {'id':3,'name':'taibai','age':16},]

# 按照年龄对学生信息进行排序

print(sorted(lst,key=lambda e:e['age']))

结果:
[{'id': 3, 'name': 'taibai', 'age': 16}, {'id': 2, 'name': 'wusir', 'age': 17}, {'id': 1, 'name': 'alex', 'age': 18}]

<4> filter () filtering filtering

def func(a):
    return a == 1

print(list(filter(func,[1,2,3,4,6])))
1,指定过滤规则(函数名[函数的内存地址])  2,要过滤的数据

自己模拟

def filter(func,argv):
    lst = []
    for i in argv:
        ret = func(i)
        if ret:
            lst.append(i)
    return lst

def foo(a):
    return a>2

print(filter(foo,[1,2,3,4])) # filter(foo,[1,2,3,4])

def func(a):
    return a>1
print(list(filter(func,[1,2,3,4,5])))

print(list(filter(lambda a:a>1,[1,2,3,4,5])))

语法: filter(function,iterable)

function: 用来筛选的函数,在filter中会自动的把iterable中的元素传递给function,然后根据function返回的True或者False来判断是否保留此项数据

iterable:可迭代对象

lst = [{'id':1,'name':'alex','age':18},
        {'id':1,'name':'wusir','age':17},
        {'id':1,'name':'taibai','age':16},]

ls = filter(lambda e:e['age'] > 16,lst)

print(list(ls))

结果:
[{'id': 1, 'name': 'alex', 'age': 18},
 {'id': 1, 'name': 'wusir', 'age': 17}]

<5> map () Mapping (iterative objects each element to perform the specified function)

def func(a,b):
    return a+b
print(list(map(func,[1,2,3,4,5],[33,22,44,55])))


def map(argv,args):
    lst = []
    num = len(args) if len(args) < len(argv) else len(argv)
    for i in range(num):
        lst.append(argv[i] + args[i])
    return lst
print(map([1,2,3,4],[3,4,5,6,7,8,9,0]))

print(list(map(lambda x,y:x+y,[1,2,3,4,5],[33,22,44,55])))
语法: map(function,iterable) 可以���可迭代对象中的每一个元素进映射,分别取执行function

计算列表中每个元素的平方,返回新列表

lst = [1,2,3,4,5]

def func(s):

    return  s*s

mp = map(func,lst)

print(mp)

print(list(mp))




改写成lambda

lst = [1,2,3,4,5]

print(list(map(lambda s:s*s,lst)))




计算两个列表中相同位置的数据的和

lst1 = [1, 2, 3, 4, 5]

lst2 = [2, 4, 6, 8, 10]

print(list(map(lambda x, y: x+y, lst1, lst2)))

结果:

[3, 6, 9, 12, 15]
Help us to do higher-order function inside a for loop

3, reduce tired calculated

from functools import reduce   # 累计算
从 functools工具箱中拿来了reduce工具
def func(x,y):
    return x+y
print(reduce(func,[1,2,3,4,5]))
print(reduce(lambda x,y:x+y,[1,2,3,4,5]))
from functools import reduce
def func(x,y):
    return x + y

# reduce 的使用方式:
# reduce(函数名,可迭代对象)  # 这两个参数必须都要有,缺一个不行

ret = reduce(func,[3,4,5,6,7])
print(ret)  # 结果 25
reduce的作用是先把列表中的前俩个元素取出计算出一个值然后临时保存着,
接下来用这个临时保存的值和列表中第三个元素进行计算,求出一个新的值将最开始
临时保存的值覆盖掉,然后在用这个新的临时值和列表中第四个元素计算.依次类推

注意:我们放进去的可迭代对象没有更改
以上这个例子我们使用sum就可以完全的实现了.我现在有[1,2,3,4]想让列表中的数变成1234,就要用到reduce了.
普通函数版
from functools import reduce

def func(x,y):

    return x * 10 + y
    # 第一次的时候 x是1 y是2  x乘以10就是10,然后加上y也就是2最终结果是12然后临时存储起来了
    # 第二次的时候x是临时存储的值12 x乘以10就是 120 然后加上y也就是3最终结果是123临时存储起来了
    # 第三次的时候x是临时存储的值123 x乘以10就是 1230 然后加上y也就是4最终结果是1234然后返回了

l = reduce(func,[1,2,3,4])
print(l)


匿名函数版
l = reduce(lambda x,y:x*10+y,[1,2,3,4])
print(l)


在Python2.x版本中recude是直接 import就可以的, Python3.x版本中需要从functools这个包中导入

龟叔本打算将 lambda 和 reduce 都从全局名字空间都移除, 舆论说龟叔不喜欢lambda 和 reduce

最后lambda没删除是因为和一个人给龟叔写了好多封,进行交流然后把lambda保住了.

Guess you like

Origin www.linuxidc.com/Linux/2019-09/160550.htm