python based learning ninth day

I. anonymous function

Anonymous function, as the name suggests is a function without a name, then what function has no name yet? This is our future interviews or work often anonymous function lambda, also called a word function.

There is now a demand: you write a function, this function receives two int parameters, and return values.

def func(a,b):
    return a+b
print(func(3,4))

So then we have completed the above requirements with anonymous functions:

func = lambda a,b: a+b
print(func(3, 4))  # 7

We analyze the above code:

grammar:

  Function name = lambda parameter: Return value

1) This function is not no name, he has a name, and his name is called lambda

2) lambda keyword to define an anonymous function, which is equivalent def function.

3) added directly behind the lambda parameter, how many can participate shape, as long as the line separated by commas.

func = lambda a,b,*args,sex= 'alex',c,**kwargs: kwargs
print(func(3, 4,c=666,name='alex'))  # {'name': 'alex'}
# 所有类型的形参都可以加,但是一般使用匿名函数只是加位置参数,其他的用不到。

4) return value after the colon, the return value and normal functions, may be of any data type. (But want to return multiple elements to be returned in the form of a container)

5) anonymous function no matter how complicated can only write a single line. And return directly after the end of the logical data

Then a small problem a few anonymous function:

Write anonymous function: receiving a data slice, returns the index of an element corresponding to 0 and 2 (form of tuples).

func = lambda x:(x[0],x[2])
print(func('afafasd'))

Write an anonymous function: int receives two parameters, the larger the data returned.

func = lambda x,y: x if x > y else y
print(func(3,100))

II. Built-in functions I

In this section we talk about built-in functions. First, the function is function-oriented, a function of a function package, then Python will be some common functions (such as len) gave us a package into a function, for our use, they are not only high efficiency (underlying all written in C language), ready to use and is used to avoid duplication early wheels, these functions are called built-in functions, built-in functions python so far provided us with a total of 68, due to time and to consider these functions we will pick the importance of different commonly used built-in functions important to say, is the following built-in functions red yellow background, the rest of the built-in functions that you practice what you can reference the class under my own blog.

Since we did not form this function, I classify these built-in functions:

The above yellow, red built-in functions in the past two days had left off (have said do not speak), blue finish will give you to add object-oriented, there are some remaining classes do not speak, lesson under practice what you can.

eval: type of code execution string, and returns the final result.

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

exec: execution string types.

s = '''
for i in [1,2,3]:
    print(i)
'''
exec(s)

Prohibit the use of two or more built-in functions very powerful work

hash: Get an object (the object may be a hash: int, str, Bool, tuple) hash value.

print(hash(12322))
print(hash('123'))
print(hash('arg'))
print(hash('alex'))
print(hash(True))
print(hash(False))
print(hash((1,2,3)))

'''
-2996001552409009098
-4637515981888139739
1
2528502973977326415
'''

help: function module or function for viewing purposes described in detail.

print(help(list))
print(help(str.split))

callable: function is used to check whether an object is callable. If it returns True, calls still may fail; 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(float(3))  # 3.0
print(complex(1,2))  # (1+2j)

bin: to convert decimal to binary and back.

oct: converted to decimal octal string and returns.

hex: decimal converted to a hexadecimal string and returns.

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: the divisor and the dividend calculation result, returns a tuple of the quotient and remainder of (a // b, a% b).

round: retention of floating-point decimal places, default retention integer.

pow: find the X- the y-th power. (Three parameters of x results of z I y taken)

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: for conversion between different coding.

# s = '你好'
# bs = s.encode('utf-8')
# print(bs)
# s1 = bs.decode('utf-8')
# print(s1)
# bs = bytes(s,encoding='utf-8')
# print(bs)
# b = '你好'.encode('gbk')
# b1 = b.decode('gbk')
# print(b1.encode('utf-8'))

ord: Enter the characters to find the character encoding of the current position

chr: enter the current position of the digital encoding to identify its corresponding character

# ord 输入字符找该字符编码的位置
# print(ord('a'))
# print(ord('中'))

# chr 输入位置数字找出其对应的字符
# print(chr(97))
# print(chr(20013))

repr: Returns a string form of the object (true colors).

# %r  原封不动的写出来
# name = 'taibai'
# print('我叫%r'%name)

# repr 原形毕露
print(repr('{"name":"alex"}'))
print('{"name":"alex"}')

all: iterables in all True is True

any: iterables, there is a True True

# all  可迭代对象中,全都是True才是True
# any  可迭代对象中,有一个True 就是True
# print(all([1,2,True,0]))
# print(any([1,'',0]))

III. Built-in functions Ⅱ

Yesterday, we've finished the more important built-in functions, and so today we talk about the most important higher-order functions and built-in functions, these built-in functions are frequently used in an interview with the work, so today these built-in functions, we must all remember, and skilled use.

Built-in functions:

str () into a string of bytes

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

list () to convert into a list iterables

print(list("alex"))

tuple () will be converted into a tuple iterables

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

dict () to convert into a list of tuples and dictionaries

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

set () converts into a collection iterables

print(set("alex"))

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: 立即把内容输出到流文件,不作缓存
    """
'''
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)

sum () sums

summing sum the object must be iterative, object elements must be an integer, string type can not be used

print(sum([1,2,3]))
print(sum([1,2,3],100))  100是起始值,就是从100开始进行求和

abs () returns the absolute value of

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

dir () to view the current object has any way

print(dir(list))

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,

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)

format () format conversion

# 对齐方式:
print(format(122,">20")) 
print(format(122,"<20"))
print(format(122,"^20"))

# 进制转换:
将十进制转换成二进制
print(format(12,"b"))
print(format(12,"08b"))

将十进制转换成八进制
print(format(12,"o"))
print(format(12,"08o"))

将二进制转换成十进制
print(format(0b11001,"d"))

将十进制转换成十六进制
print(format(17,"x"))
print(format(17,"08x"))

reversed () will be a sequence of flip flip iterator returns reversed exemplary sequence:

l = reversed('你好')  # l 获取到的是一个生成器
print(list(l))
ret = reversed([1, 4, 3, 7, 9])
print(list(ret))  # [9, 7, 3, 4, 1]

Higher-order functions:

filter filter filter

语法: 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}]

map map

映射函数

语法: 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]

sorted sort function

语法: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}]

max () same as the maximum and minimum usage

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

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

reduce computing tired

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保住了.

References:

https://www.processon.com/view/link/5b4ee15be4b0edb750de96ac

Guess you like

Origin www.cnblogs.com/bky20061005/p/12145013.html