元组在for循环中解压缩

Tal*_*sin 52 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")
Run Code Online (Sandbox Code Playgroud)

我不明白'i,a'位和搜索谷歌有关'for'的信息是一个痛苦的屁股,当我尝试和代码使用时我得到错误:

ValueError:需要多于1个值才能解压缩

有谁知道它做了什么或与它有关,我可以谷歌了解更多?

Bre*_*arn 95

你可以google"tuple unpacking".这可以在Python的各个地方使用.最简单的就是任务

>>> x = (1,2)
>>> a, b = x
>>> a
1
>>> b
2
Run Code Online (Sandbox Code Playgroud)

在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
Run Code Online (Sandbox Code Playgroud)

枚举函数创建一个可迭代的元组,因此可以这种方式使用它.


nat*_*ill 16

枚举基本上为您提供了在for循环中使用的索引.所以:

for i,a in enumerate([4, 5, 6, 7]):
    print i, ": ", a
Run Code Online (Sandbox Code Playgroud)

会打印:

0: 4
1: 5
2: 6
3: 7
Run Code Online (Sandbox Code Playgroud)


ste*_*eve 7

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

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)
Run Code Online (Sandbox Code Playgroud)

印刷

0 alice alice@example.com dog
1 bob bob@example.com cat
2 fred fred@example.com parrot
Run Code Online (Sandbox Code Playgroud)


whi*_*whi 6

[i for i in enumerate(['a','b','c'])]
Run Code Online (Sandbox Code Playgroud)

结果:

[(0, 'a'), (1, 'b'), (2, 'c')]
Run Code Online (Sandbox Code Playgroud)

  • 你好,你在这里做的这个功能有名字吗?谷歌似乎并不富有成效。`[i for i in enumerate(['a','b','c'])]` (2认同)

Ble*_*der 5

以此代码为例:

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

for element in elements:
  print element, index
  index += 1
Run Code Online (Sandbox Code Playgroud)

您遍历列表并存储索引变量.enumerate()做同样的事情,但更简洁:

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

for index, element in enumerate(elements):
  print element, index
Run Code Online (Sandbox Code Playgroud)

index, element符号是必需的,因为enumerate返回一个元组((1, 'a'),(2, 'b')即解压到两个不同的变量,...).