python - "enumerate"如何知道何时解包返回值?

标签 python iterator

示例 1

for i, v in enumerate({'a', 'b'}):
    print(i, v)

返回

0 a
1 b

示例 2

for x in enumerate({'a', 'b'}):
    print(x)

返回

(0, 'a')
(1, 'b')

但是 enumerate 如何知道何时解包它返回的值?

最佳答案

enumerate() 对解包一无所知。执行此操作的是 for 语句。

for 语句的 target 部分就像常规赋值一样,您可以命名多个目标,右侧的值应该是一个序列具有相同数量的元素。 enumerate() 总是 生成两个元素的元组;您的第一个 for 循环有两个要解压的目标,第二个只有一个目标。

原理与将元组分配给两个名称的原理相同:

i, v = (0, 'a')

对比

x = (0, 'a')

参见 for statement documentation :

Each item in turn is assigned to the target list using the standard rules for assignments

以及 assignment statements documentation ,其中解释了目标列表的分配规则:

Assignment of an object to a target list is recursively defined as follows.

  • If the target list is a single target: The object is assigned to that target.
  • If the target list is a comma-separated list of targets: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets.

当您使用 just for x in 时,您有一个目标并且 (0, 'a') 元组分配给它.当您使用 for i, v in 时,您有一个逗号分隔的目标列表,元组是一个可迭代的,具有与目标相同数量的项目,因此 0 是绑定(bind)到 i'a' 绑定(bind)到 v

关于python - "enumerate"如何知道何时解包返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25526480/

相关文章:

python - 找不到包 "libapache2-mod-proxy-html"Ubuntu 16.04

python - 如何返回 numpy 数组的列主迭代器?

java - Java 枚举/迭代器的使用

python - 防止成员对象引用同一个列表

python - 在 C++ 中运行 python

python - Mac OS 10.6.2 Snow Leopard 上的 Django + MySQL

python - 当将 text() 与 python-escpos 一起使用时,我得到 [Errno None] 和关键错误 = 1 (windows 10)

c++ - STL 迭代器上下文中的奇异值和非奇异值是什么?

arrays - Kotlin 中二维数组的展平迭代器

c++ - 具有特殊情况实现的迭代器