981377660LMT / ts

ts学习
6 stars 1 forks source link

python 连续赋值顺序的坑 #551

Open 981377660LMT opened 4 months ago

981377660LMT commented 4 months ago

image image

981377660LMT commented 4 months ago

https://chowyi.com/key-points-of-chained-assignment-in-python/

981377660LMT commented 4 months ago
key, data[key] = data[key], root
data = {1: 2, 2: 3}
key = 1
root = 4

key, data[key] = data[key], root

print(key)  # 输出: 2
print(data)  # 输出: {1: 2, 2: 4}
func main() {
    data := map[int]int{1: 2, 2: 3}
    key := 1
    root := 4

    key, data[key] = data[key], root

    fmt.Println(key)       // 输出: 2
    fmt.Println(data)      // 输出: map[1:4 2:3]
}

golang:先求出右侧所有表达式的值,再统一赋值给左侧 python:遍历一个赋值一个

981377660LMT commented 4 months ago

https://stackoverflow.com/questions/33835607/tricky-order-of-evaluation-in-multiple-assignment

981377660LMT commented 4 months ago

If the target list is a comma-separated list of targets: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets. 如果目标列表是逗号分隔的目标列表:该对象必须是一个可迭代对象,其项目数与目标列表中的目标数量相同,并且项目从左到右分配给相应的目标。

981377660LMT commented 4 months ago

k[s], k[s] = k[s], None

相当于

t = k[s] k[s] = t k[s] = None

当右侧是动态可迭代对象(例如生成器)时,求值顺序也成立。所有必要的元素将首先被提取并从左到右分配