A triplet of expressions
What is a ternary expression?
if ... else statements can be combined into a branch line of code
Why ternary expression?
A triplet of expressions is a simplified code python for us to provide solutions
How ternary expression?
Else condition determination condition value if condition is established res = return value returned is not satisfied
Scenarios
#不使用三元表达式方法
def max2(x, y):
if x > y:
return x
else:
return y
res = max2(1, 2)
print(res)
#结果为
2
#使用三元表达式时
x = 1
y = 2
res = x if x > y else y
print(res)
#结果为
2
# 需求: 让用户输入用户名,输入的用户如果不是bing缀添加_DSB
username = input('请输入你的用户名:')
res = username if username == 'bing' else username + '_DSB'
print(res)
List of Formula
What is a list of the formula?
You can generate a list of his party achieved.
Why use a list of formula?
List of Formula is a simplified solution python code that provides us used to quickly generate a list of
How the formula with a list?
grammar:
list = [a value taken for each, can be any value + for + each iteration a value in the extracted object iterable]
is right for the number of cycles, and may be taken to add the current value of the left list is a value # for each iteration may be subject
Scenarios
#不使用列表生成式
egg_list = []
for i in range(10):
egg_list.append('鸡蛋%s' % i)
print(egg_list)
#结果为
['鸡蛋0', '鸡蛋1', '鸡蛋2', '鸡蛋3', '鸡蛋4', '鸡蛋5', '鸡蛋6', '鸡蛋7', '鸡蛋8', '鸡蛋9']
#使用列表生成式
egg_list = ['鸡蛋%s'%i for i in range(10)]
print(egg_list)
#结果为
['鸡蛋0', '鸡蛋1', '鸡蛋2', '鸡蛋3', '鸡蛋4', '鸡蛋5', '鸡蛋6', '鸡蛋7', '鸡蛋8', '鸡蛋9']
Generator expression (formula)
Creating a generator object in two ways, one is a function call with a yield keyword is the same as another generator expression, and generate a list of syntax, just [] replace ()
grammar:
() ---> Returns generator
(Line for line in range (1, 6)) ---> g generators (1, 2, 3, 4, 5)
Comparison with the list generator expression Builder
#1.对比列表生成式返回的是一个列表,生成器表达式返回的是一个生成器对象
list = [x*x for x in range(3)]
print(list)
g = (x*x for x in range(3))
print(g)
#结果为
[0, 1, 4]
<generator object <genexpr> at 0x000001E821B321C8>
#对比列表生成式,生成器表达式的优点自然是节省内存(一次只产生一个值在内存中)
#总结:列表生成式与生成器表达式优缺点以及应用场景
#列表生成式
#优点:因为其返回的是一个列表,所以可以依赖索引取值
#缺点:占用内存空间大(一次性将所有值读入内存),容易造成资源浪费
#生成器表达式
#优点:占用内存空间小,节省资源(一次只取一个值)
#缺点:去某个特定的值不方便