相关链接:
1.基础与增强赋值语句https://blog.csdn.net/riven78/article/details/147119792
2.*重要*赋值表达式详解https://blog.csdn.net/riven78/article/details/147120067
在 Python 中,赋值语句用于将值或对象与变量名绑定。
assignment_stmt ::= (target_list "=")+ (starred_expression | yield_expression)
target_list ::= target ("," target)* [","]
target ::= identifier
| "(" [target_list] ")"
| "[" [target_list] "]"
| attributeref
| subscription
| slicing
| "*" target
用=将右侧的值赋给左侧的变量:
a = 10 # 整数
name = "Alice" # 字符串
lst = [1, 2, 3] # 列表
多个变量指向同一个值:
x = y = z = 0 # x, y, z 都赋值为 0
将序列(列表、元组等)中的值按顺序分配给变量:
a, b = 1, 2 # a=1, b=2
x, y, z = [10, 20, 30]
使用*解包剩余元素
first, *rest = [1, 2, 3, 4] # first=1, rest=[2,3,4]
*front, last = "hello" # front=['h','e','l','l'], last='o'
通过解包直接交换变量:
a, b = b, a # 交换 a 和 b 的值
Python 中变量是对象的引用(而非值的拷贝)。
对可变对象(如列表)的修改会影响所有引用该对象的变量:
list1 = [1, 2, 3]
list2 = list1
list2.append(4) # list1 也会变为 [1,2,3,4]
字典键赋值:
d = {}
d["key"] = "value"
对象属性赋值:
class MyClass: pass
obj = MyClass()
obj.attr = 42
增强赋值语句就是在单个语句中将二元运算和赋值语句合为一体:
augmented_assignment_stmt ::= augtarget augop (expression_list | yield_expression)
augtarget ::= identifier | attributeref | subscription | slicing
augop ::= "+=" | "-=" | "*=" | "@=" | "/=" | "//=" | "%=" | "**="
| ">>=" | "<<=" | "&=" | "^=" | "|="
简化对变量的运算并重新赋值:
a += 1 # 等价于 a = a + 1
b *= 2 # 等价于 b = b * 2
s += "!" # 字符串追加
在表达式中赋值变量:
# 在条件判断中赋值并检查
if (n := len("hello")) > 3:
print(f"长度是 {n}") # 输出:长度是 5
a, b = [1, 2, 3] # ValueError: 元素数量不一致
使用避免错误:*
a, *b = [1, 2, 3] # a=1, b=[2,3]
a = [1, 2]
b = a
b = 99 # a 也会变为 [99, 2]
如需独立拷贝,使用copy()或切片:
b = a.copy() # 或 b = a[:]
下一篇:
2. *重要*赋值表达式详解 https://blog.csdn.net/riven78/article/details/147120067