我偶然发现了以下代码:
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/