我是python初学者。我最近了解到列表和元组允许赋值。## 1)a=[1,2,3,4][j,c,d,f] = aprint (j) # prints 1## 2)t=(6,7,8,9)(s1,s2,s3,s4) = tprint (s1) # prints 6## 3)m={11,12,13}{s,d,c}=mprint(s) #Gives error我无法理解这种行为。为什么与 set 的类似操作会出错。此外,字典也可以进行类似的操作?请帮助和解释。
2 回答

慕虎7371278
TA贡献1802条经验 获得超4个赞
您在列表和元组中看到的行为称为可迭代解包,用于将任何序列中的值解包为变量(只要左侧的变量与右侧的变量一样多——除非您使用扩展的可迭代开箱)。
给定的
a = [1, 2, 3, 4]
b = (1, 2, 3, 4)
c = {1, 2, 3, 4}
以下是所有有效的操作:
e, f, g, h = a
# Equivalent to
# (e, f, g, h) = a
# Also equivalent to, but slightly different than
# [e, f, g, h] = a
w, x, y, z = b
p, q, r, s = c
但是,集合不支持该语法,因为它们没有任何固有的顺序(至少在 python3.6 之前没有)。所以,
{p, q, r, s} = a
是无效语法 ( SyntaxError: can't assign to literal) 因为python 的语法规范不支持它。
添加回答
举报
0/150
提交
取消