一、三元表达式
1 a = ‘骑车‘ 2 3 res = ‘好天气‘ if a == ‘骑车‘ else ‘睡觉‘ 4 print(res)
1 睡觉
解析:res = ‘好天气‘ if a == ‘骑车‘ else ‘睡觉‘ ,将一个句子分了三部分。简单的逻辑运算可用这种三元表达式
二、列表解析
1 gift_list = [] 2 for i in range(10): 3 gift_list.append(‘礼盒%s‘%i) 4 print(gift_list) 5 6 gift_list1 = [‘礼盒%s‘%i for i in range(10)] 7 print(gift_list1) 8 9 gift_list2 = [‘礼盒%s‘%i for i in range(10) if i > 5] 10 print(gift_list2) 11 12 #gift_list3 = [‘礼盒%s‘%i for i in range(10) if i > 5 else i <=5] # 报错,最多只有三元,没有四元以及更多
解析:通过运用三元表达式,可以简化代码。而且更省内存,效率更高
1 [‘礼盒0‘, ‘礼盒1‘, ‘礼盒2‘, ‘礼盒3‘, ‘礼盒4‘, ‘礼盒5‘, ‘礼盒6‘, ‘礼盒7‘, ‘礼盒8‘, ‘礼盒9‘] 2 [‘礼盒0‘, ‘礼盒1‘, ‘礼盒2‘, ‘礼盒3‘, ‘礼盒4‘, ‘礼盒5‘, ‘礼盒6‘, ‘礼盒7‘, ‘礼盒8‘, ‘礼盒9‘] 3 [‘礼盒6‘, ‘礼盒7‘, ‘礼盒8‘, ‘礼盒9‘]
原文地址:https://www.cnblogs.com/jianguo221/p/8976855.html
时间: 2024-11-05 16:30:42