python - 元组如何在 for 循环中解包?

标签 python python-3.x tuples iterable-unpacking

我偶然发现了以下代码:

for i, a in enumerate(attributes):
   labels.append(Label(root, text = a, justify = LEFT).grid(sticky = W))
   e = Entry(root)
   e.grid(column=1, row=i)
   entries.append(e)
   entries[i].insert(INSERT,"text to insert")

我不理解 i, a 位,并且搜索有关 for 的信息没有产生任何有用的结果。当我尝试使用代码时,我得到了错误:

ValueError: need more than 1 value to unpack

有谁知道它的作用,或者与它相关的更具体的术语,我可以通过谷歌了解更多信息?

最佳答案

你可以谷歌"tuple unpacking" .这可以在 Python 的各个地方使用。最简单的就是赋值:

>>> x = (1,2)
>>> a, b = x
>>> a
1
>>> b
2

在 for 循环中它的工作方式类似。如果iterable的每个元素都是一个tuple,那么可以指定两个变量,循环中的每个元素都会解包到这两个。

>>> x = [(1,2), (3,4), (5,6)]
>>> for item in x:
...     print "A tuple", item
A tuple (1, 2)
A tuple (3, 4)
A tuple (5, 6)
>>> for a, b in x:
...     print "First", a, "then", b
First 1 then 2
First 3 then 4
First 5 then 6

enumerate 函数创建一个可迭代的元组,因此可以这样使用。

关于python - 元组如何在 for 循环中解包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10867882/

相关文章:

python - 字典 Python 中 If-Condition 上的 KeyError

python - 在python中提取URL的信息部分

python - 从 python 将数据推送到 redshift 数据库时语句太大

Python 正则表达式 - 为什么字符串结尾 ($ 和\Z) 不适用于组表达式?

python - 我的第一个 if 语句总是 True。没有引发错误或异常

python - 使用 PyInstaller 自定义日志处理程序和格式化程序

python - 比较两个元组的所有元素(使用 all() 功能)

javascript - 从 RESTful 服务查看主干数据

python - 使用索引切片打印字符串中的每个单词

Python:元组中的列表