示例 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/