Advanced functions (2)

1. a triplet of expressions

Return Values ​​When the condition else if condition is not satisfied when the conditions are satisfied

dog_name = 'crazy_dog'

if dog_name == 'crazy_dog':
    print('1')
else:
    print('2')

# 三元表达式/列表推导式/字典生成式,只是让你的代码代码更少了,但是逻辑没有变化
print('1') if dog_name == 'crazy_dog' else print('2')

2. List comprehensions

lt = [0,1,2,3,4]

lt = []
for i in range(10):
    lt.append(i)
print(lt)

lt = [i for i in range(10)]
print(lt)

lt = []
for i in range(10):
    lt.append(i**2)
print(lt)

lt = [i**2 for i in range(10)]
print(lt)

dic = {'a':1,'b':2}

lt1 = [i for i in dic.items()]
print(lt1)

lt = [(k,v) for (k,v) in dic.items()]
print(lt)

3. Dictionary of formula

dic = {'a':1,'b':2}

new_dic = {k*2:v**2 for k,v in dic.items()}
print(new_dic)  # {'aa': 1, 'bb': 4}

# 字典生成式一般与zip(拉链函数--》列表里面包了元组)联用
z = zip([1,2,3,4],[1,2,3,4]) # 压缩方法,python解释器的内置方法
print(z.__next__())  # (1, 1)
print(z.__next__())  # (2, 2)

z = zip([1, 2, 3, 4], [1, 2, 3, 4])  # 压缩方法,python解释器的内置方法
for k, v in z:
    print(k, v)

z = zip([1, 2, 3, 4], [1, 2, 3, 4])
dic = {k ** 2: v ** 2 for k, v in z}
print(dic)   # {1: 1, 4: 4, 9: 9, 16: 16}

z = zip(['a','b','c','d'], [1, 2, 3, 4])
dic = {k:v for k,v in z}
print(dic)  # {'a': 1, 'b': 2, 'c': 3, 'd': 4}

4. Generator

Builder: Custom iterators, generators iterators (made out of their own).

the yield keyword: Whenever the yield keyword appears in a function, and then call the function, the function body will not continue to execute the code, but will return a value.

Iterator object: a __iter__, __next__method

def func():
    yield 456 # yield会使函数func()变成生成器对象,因此他就具有__iter__方法
    print(789) # yield会停止函数,当运行下一次next才会继续运行下面的代码
    yield 101112  # 一个yield对应一个next
    print(131415)

f = func() # 生成器
print(f)   # <generator object func at 0x000001A294AD4ED0>
f_iter = f.__iter__()
print(f_iter.__next__())
print(f_iter.__next__())
# print(f_iter.__next__()) # 报错

yield of three characteristics :

  1. yield function can become generator (custom iterator object having __iter__Method)

2.yield can stop the function, the next time the next run yield the following code again

3. The yield of n generators have n elements, n can next time, the next time n + 1 will be given

return characteristics :

1. Return value

2. termination function

def func():
    yield [1,1,23] 
    print(789) 
    yield 101112 
    print(131415)

g = func()
for i in g:
    print(i)

A method of using customized range generator

# 1. 生成一个可迭代器对象 --- 》 我要把我的range函数变成一个可迭代对象(迭代器对象)
# 2. 丢一个10进去,然后通过for循环的迭代next会丢出0,1,2,3,4,5,6,7,8,9

def range(x):
    count = 0
    while count < x:
        yield count
        count += 1
        
for i in range(10):
    print(i)

The generator expression

# 把列表推导式的[]换成()
lt = [i for i in range(10)]
print(lt)
g = (i for i in range(10))
print(g)
print(g.__next__())

# 列表和元组的区别
# 列表就是一筐鸡蛋,元组就是一只老母鸡(节省空间,一次只产生一个值在内存中)

6. anonymous function

Functions are well-known function that we previously defined, which is based on the use of the function name.

def max2(x,y):
    if x > y:
        return x
    return y

res = max(10,20)
print(res)

Anonymous function, he has no name binding, ie, once recovered, either bracketed run.

Keyword need anonymous lambda.

lambda Parameters: <block>

f = lambda x: x+1
res = f(1)
print(res)

Anonymous functions generally not used alone, and the filter () / map () / sorted () / sort the list () method associated with built

salary_dict = {
    'nick': 3000,
    'jason': 100000,
    'tank': 5000,
    'sean': 2000
}
salary_list = list(salary_dict.items())
# print(salary_list)

def func(i):  # i=('sean', 2000), ('nick', 3000),('tank', 5000),('jason', 100000)
    return i[1]  # 2000,3000,5000,100000

salary_list.sort(key=lambda i:i[0]) # 内置方法是对原值排序
# 按照func的规则取出一堆元素2000,3000,5000,100000
# 然后按照取出的元素排序
print(salary_list)

new_salary_list = sorted(salary_list,key=lambda i:i[1],reverse=True)  # 重新创建一个新的列表进行排序
print(new_salary_list)

# max():找出薪资最高的人
print(max(salary_list,key=lambda i:i[1]))
# min():找出薪资最低的人
print(min(salary_list,key=lambda i:i[1]))

# filter():对列表中的人做筛选
print(list(filter(lambda i:i[1] < 5000,salary_list)))

# map():对一个列表中的人做处理
print(list(map(lambda i:i[1] + 2000,salary_list)))

Guess you like

Origin www.cnblogs.com/yushan1/p/11345690.html