python - 了解序列解包 : Why does using a set throw "SyntaxError: can' t assign to literal"?

标签 python python-3.x

我是一名 Python 初学者。我最近了解到列表和元组允许赋值。

## 1)
a=[1,2,3,4]
[j,c,d,f] = a
print (j)  # prints 1
## 2)
t=(6,7,8,9)
(s1,s2,s3,s4) = t
print (s1)  # prints 6
## 3)
m={11,12,13}
{s,d,c}=m
print(s)     #Gives error

我无法理解这种行为。为什么与 set 类似的操作会出错。另外,字典也可以进行类似的操作吗? 请帮助和解释。

最佳答案

您在列表和元组中看到的行为称为可迭代解包,用于将任何序列中的值解包到变量中(只要左边的变量与右边的变量一样多)右边——除非你使用 extended iterable unpacking )。

给定

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:无法分配给文字)因为python's grammar specification不支持。

关于python - 了解序列解包 : Why does using a set throw "SyntaxError: can' t assign to literal"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53922731/

相关文章:

Python OOP - 网络 session

python - 具有不同表达式的 Lambda 返回相同的输出

python - 强制 Nosetests 使用 Python 2.7 而不是 3.4

python - 用 str、float、int 和元组除法

python - matplotlib 的轴标记太稀疏

python - 如何将数据框/列表写入 csv 文件?

python - Pandas 不稳定地返回 TypeError 无法使用 <class 'pandas.core.indexes.base.Index' > 的这些索引器 [310] 对 <class 'int' > 进行切片索引

python - 将物体正确导入 flask 中? Flask 无法导入名称邮件

python-3.x - 使用 glob.glob() 读取时如何排除某些文件?

python - Keras:实际使用的 GPU 内存量