列表推导式可以简化列表循环
"""快速生成一个包含1-20数字的列表"""
list1 = [i for i in range(1,21)]
"""快速生成一个包含1-20之间能被3整除的所有数字列表"""
list2 = [i for i in range(1,21) if i%3==0]
"""快速生成一个包含1-20之间能被3整除的所有数字的平方列表"""
list3 = [i*i for i in range(1,21) if i%3==0]
test = [1,2,3,4,5,6,7,8,9,10]
"""使用普通循环"""
list1 = []
for i in test:
if i%2==0:
list1.append(i)
"""使用filter"""
list2 = list(filter(lambda i:i%2==0,test))
"""使用列表推导式"""
list3 = [i for i in test if i%2==0]
test = ["1","2","3","4","5","6","7","8","9","10"]
"""使用普通循环"""
list1 = []
for i in test:
list1.append(int(i))
"""使用filter"""
list2 = list(map(lambda i:int(i),test))
"""使用列表推导式"""
list3 = [int(i) for i in test]
"""使用普通循环"""
list1 = []
for i in range(1,5):
for j in range(1,i):
if j%2 == 0:
list1.append((i,j))
"""使用列表推导式"""
list2 = [(i,j) for i in range(1,5) for j in range(1,i) if j%2==0]
字典推导式可以简化字典循环
test = {"a":5,"B":10,"c":15,"D":20}
"""使用普通循环"""
dict1 = {}
for k,v in test.items():
dict1[k.upper()] = v
"""使用字典推导式"""
dict2 = {k.upper():v for k,v in test.items()}
test = {"a":5,"B":10,"c":15,"D":20}
"""使用普通循环"""
dict1 = {}
for k,v in test.items():
if v%2==0:
dict1[k] = v
"""使用字典推导式"""
dict2 = {k:v for k,v in test.items() if v%2==0}
三目运算符可以简化选择
格式:exp1 if 条件语句 else exp2
运行过程:如果条件语句为真,就执行并返回exp1,否则就执行并返回 exp2
"""简化前"""
if a>b:
max = a;
else:
max = b;
"""简化后"""
max = a if a>b else b