元组在 for 循环中解包 [英] Tuple unpacking in for loops

查看:61
本文介绍了元组在 for 循环中解包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶然发现了以下代码:

for i,a in enumerate(attributes):label.append(Label(root, text = a, justify = LEFT).grid(sticky = W))e = 条目(根)e.grid(列=1,行=i)entry.append(e)entry[i].insert(INSERT,"要插入的文本")

我不明白 'i,a' 位,在 google 上搜索有关 'for' 的信息很麻烦,当我尝试使用代码进行实验时,出现错误:

<块引用>

ValueError: 需要 1 个以上的值来解包

有谁知道它有什么作用或与它有什么关系,我可以谷歌了解更多信息?

解决方案

你可以谷歌搜索元组解包".这可以用在 Python 的各个地方.最简单的就是赋值

<预><代码>>>>x = (1,2)>>>a, b = x>>>一种1>>>乙2

在 for 循环中,它的工作原理类似.如果迭代器的每个元素都是一个元组,那么你可以指定两个变量,循环中的每个元素都会被解包为两个.

<预><代码>>>>x = [(1,2), (3,4), (5,6)]>>>对于 x 中的项目:...打印元组",项目元组 (1, 2)元组 (3, 4)元组 (5, 6)>>>对于 a, b 在 x 中:...打印第一个",a,然后",b先1然后2先3后4先5后6

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

I stumbled across the following code:

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 don't understand the 'i,a' bit and searching google for information on 'for' is a pain in the bum and when I try and experement with the code I get the error:

ValueError: need more than 1 value to unpack

Does anyone know what it does or something to do with it that I can google to learn more?

解决方案

You could google on "tuple unpacking". This can be used in various places in Python. The simplest is in assignment

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

In a for loop it works similarly. If each element of the iterable is a tuple, then you can specify two variables and each element in the loop will be unpacked to the two.

>>> 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

The enumerate function creates an iterable of tuples, so it can be used this way.

这篇关于元组在 for 循环中解包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆