Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在for循环中解包元组_Python_Python 3.x - Fatal编程技术网

Python 在for循环中解包元组

Python 在for循环中解包元组,python,python-3.x,Python,Python 3.x,我偶然发现了以下代码: 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 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:需要超过1个值才能解包

有没有人知道它做了什么或与它有什么关系,我可以通过谷歌了解更多信息?

你可以通过谷歌搜索“元组解包”。这可以在Python中的不同位置使用。最简单的是分配

>>> x = (1,2)
>>> a, b = x
>>> a
1
>>> b
2
在for循环中,它的工作原理类似。如果iterable的每个元素都是一个元组,那么可以指定两个变量,循环中的每个元素都将被解包为两个变量

>>> 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函数创建一个元组的iterable,因此可以这样使用。

enumerate函数返回一个生成器对象,该对象在每次迭代时生成一个元组,其中包含元素(
i
)的索引,默认情况下从
0
开始编号,并与元素本身(
a
)相结合,而且,
for
循环方便地允许您访问生成的元组的两个字段,并为它们分配变量名。

枚举基本上为您提供了在for循环中使用的索引。因此:

for i,a in enumerate([4, 5, 6, 7]):
    print i, ": ", a
将打印:

0: 4
1: 5
2: 6
3: 7

以该代码为例:

elements = ['a', 'b', 'c', 'd', 'e']
index = 0

for element in elements:
  print element, index
  index += 1
在列表上循环并存储索引变量
enumerate()
做同样的事情,但更简洁:

elements = ['a', 'b', 'c', 'd', 'e']

for index, element in enumerate(elements):
  print element, index
由于
枚举
返回的元组(
(1,'a')
(2,'b')
,…)被解压为两个不同的变量,因此需要
索引,元素
符号

[i for i in enumerate(['a','b','c'])]
结果:

[(0, 'a'), (1, 'b'), (2, 'c')]

简而言之,在for循环中从列表中解包元组是有效的。 enumerate()使用当前索引和整个当前项创建元组,例如(0,('bob',3))

我创建了一些测试代码来演示这一点:

    list = [('bob', 3), ('alice', 0), ('john', 5), ('chris', 4), ('alex', 2)]

    print("Displaying Enumerated List")
    for name, num in enumerate(list):
        print("{0}: {1}".format(name, num))

    print("Display Normal Iteration though List")
    for name, num in list:
        print("{0}: {1}".format(name, num))

元组解包的简单性可能是我最喜欢的Python之一:D

您可以将索引、值的
方法与使用
()
直接解包元组相结合。当您想在循环中设置几个相关的值,这些值可以在没有中间元组变量或字典的情况下表达时,这非常有用,例如

users = [
    ('alice', 'alice@example.com', 'dog'),
    ('bob', 'bob@example.com', 'cat'),
    ('fred', 'fred@example.com', 'parrot'),
]

for index, (name, addr, pet) in enumerate(users):
    print(index, name, addr, pet)
印刷品

0 alice alice@example.com dog
1 bob bob@example.com cat
2 fred fred@example.com parrot

您好,您在这里使用的这个功能有名字吗?谷歌似乎并不富有成效<代码>[i for i in enumerate(['a','b','c'])]
这叫做感谢,这正是我要找的。已经知道如何使用
enumerate
,但不知道idx的
(name,addr,pet)
元组解包方法。干杯