[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
3.4 Python表达式
Python表达式是运算符和操作数进行有意义排列所得的组合。操作数可以是值、变量、标识符等。单独的一个值或一个变量也是一个表达式。
表达式是Python程序中最常见的代码。
表达式是一段可以被求值的代码。因为可以被求值,所以一般表达式可以写在赋值语句=的右边。表达式可以作为语句的组成部分。
以下都是Python表达式:
5 + 3
3 ** 2
-66
a > 3
b == c
d in e
f is not g
not h
3.4.1 赋值表达式
一个常见用例是在处理匹配的正则表达式的时候:
if matching := pattern.search(data):
do_something(matching)
或者是在处理分块的文件流的时候:
while chunk := file.read(9000):
process(chunk)
3.4.2 条件表达式
条件表达式(有时称为三元运算符)在所有 Python 运算中具有最低的优先级。表达式 x if C else y 首先是对条件 C 而非 x 求值。如果 C
为真,x 将被求值并返回其值;否则将对 y 求值并返回其值。其语法格式为:
为真时 if 条件表达式 else 为假时 # 斜体为需要替换的内容,下同
示例1:
>>> a = 5 if 3 > 2 else 1
>>> a
5
示例2
>>> print('hello') if 5 == 33 else print('world')
world
3.4.3 lambda 表达式
lambda 表达式(有时称为 lambda 构型)被用于创建匿名函数。表达式:
lambda 参数: 表达式
会产生一个函数对象。该未命名对象的行为类似于用以下方式定义的函数:
def <lambda>(*参数*):
return 表达式
关于lambda表达式我们将会在函数章节进行详细介绍。
3.4.4 表达式的求值顺序
Python 按从左至右的顺序对表达式求值。但注意在对赋值操作求值时,右侧会先于左侧被求值。
练习
1、将教程中所有的表达式示例全部手敲一遍并熟悉