A ternary operator (ternary operator)
That is if ... else ... syntactic sugar, using the premise else and if only one statement.
grammar
result = 结果一条件成立时执行 if 条件 else 结果二条件不成立时执行
Results ternary operator does not necessarily have a direct relationship with the conditions
a = 20
b = 30
res = a if a > b else b # 求大值
print(res)
res = b if a > b else a # 求小值
print(res)
Second, derivations
List (tuples) syntactic sugar conversion dictionary
listing derivation formula
dic = {'a': 1, 'b': 2, 'c': 3} # => [('a', 1), ('b', 2), ('c', 3)]
res = [(k, v) for k, v in dic.items()]
print(res)
Derivation of formula tuple
res = ((k, v) for k, v in dic.items())
print(tuple(res))
Dictionary derivations
ls = [('a', 1), ('b', 2), ('c', 3)] # => {'a': 1, 'b': 2, 'c': 3}
res = {k: v for k, v in ls}
print(res)
Case
可以被推导为列表
range(10)
res_ls = [arg for arg in range(10)]
print(res_ls) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
推导字典只保留最后一个数据
res_dic = {'a': arg for arg in range(10)}
print(res_dic) # {'a': 9}
迭代出可解压为的单列容器可以推导出字典
res_dic = {v: k for k, v in enumerate('abc')}
print(res_dic) # {'a': 0, 'b': 1, 'c': 2}
Second, recursive
Backtracking and recursion
- Back: answer the inquiry process
- Recursive: the launch of the process of the answer
Recursive premise
- Back to a specific value of the result, start Recursive
- Conditions should be the law of backtracking and recursion
Two ways
Recursive nature is self-calling function
(1). Own their own tune
def a():
global count
count += 1
if count > 50:
return
a()
a()
(2) function calls between each other form a circulation
def b():
c()
def c():
d()
def d():
b()
b()
Case
阶乘
def factorial(num):
if num == 1:
return 1
temp = num * factorial(num - 1)
return temp
res = factorial(5)
print(res)
Third, the anonymous function
As the name suggests, there is no function name, no function body, only a return value
grammar
lambda parameter list omitted (): Returns the value of the expression a return keyword also omitted
Scenarios
1. anonymous function address can be a variable to accept, as a function of the variable names can be used, but it is contrary to the original intention of anonymity
2. The combination of built-in functions to use: built-in functions require a certain parameter function address
- can be assigned a well-known function name, you can also directly assign an anonymous function
薪资最高
iterable = {
'Bob': 12000,
'Tom': 37000,
'Jerry': 76000,
'Zero': 120,
}
res = max(iterable, key=lambda x: iterable[x]) # x: 字典的k 返回值:做比较的值
print(res)
iterable = {
'Bob': {'no': 100, 'salary': 12000},
'Tom': {'no': 200, 'salary': 37000},
'Jerry': {'no': 50, 'salary': 76000},
'Zero': {'no': 150, 'salary': 120},
}
res = max(iterable, key=lambda k: iterable[k]['no'])
print(res) # Tom 编号最高
res = max(iterable, key=lambda k: iterable[k]['salary'])
print(res) # Jerry 薪资最高