Various expressions

Various expressions

A ternary expression

For chestnuts to clear out

name = 'jiayi'
if name == 'jiayi'
    print('hahaha')
else:
    print('xixixi')
===========================================================
print('hahaha') if name == 'jiayi' else print('xixixi')
#上下两个代码的性质是一样的,这就是三元表达式

A triplet of expressions only supports dual-branch structure

Second, the list comprehension of formula

For chestnuts to clear out

lt = [0,1,2,3,4]
lt = []
for i in range(10):
    lt.append(i**2)
print(lt)
==========================================================
lt = [i for i in range(10)]
print(lt)
#上下两个代码的性质是一样的,这就是列表推导式
#而且lt = [i for i in range(10)]的第一个i可以进行算数运算,比如:lt = [i ** 2 for i in range(10)]

Third, the Dictionary of formula

For chestnuts to clear out

z = zip(['a','b','c','d'],[1,2,3,4])
for k,v in z:
    print(k,v)
# 字典生成式一般与zip(拉链函数--》列表里面包了元组)连用
dic = {k:v**2 for k,v in zip(['a','b','c','d'],[1,2,3,4])}  #压缩方法,Python解释器的内置方法
print(dic)
------------------------------------------------------------
b 2
c 3
d 4
{'a': 1, 'b': 4, 'c': 9, 'd': 16}

Guess you like

Origin www.cnblogs.com/yanjiayi098-001/p/11348041.html