python - 为什么 for 中的逗号分隔迭代不像 zip 那样工作?

标签 python python-3.x iterable-unpacking

我想理解的是为什么会出现下面的代码

for x, y in [1,2], [3,4]:
    print(x, y, x + y)

打印

1 2 3
3 4 7

代替

1 3 4
2 4 6

现在,我知道 zip 可以完成这项工作并且 not using zip to iterate over a pair of lists could be considered an anti-pattern ,但我仍然需要对此默认行为的解释。

在我看来,上面的代码应该像内置的 zip 函数一样直观地工作

for (x, y) in zip([1,2], [3,4]):
    print(x, y, x + y)

打印

1 3 4
2 4 6

从内存中我记得很久以前看到过这种技术的解释(我想这就是为什么首先想到这个解决方案的原因),但我现在已经进行了搜索,包括 Python 3 文档的整个第 5 节但是我找不到对此行为的任何解释,甚至在 section 5.6. (Looping Techniques) 上也找不到。 .

这是第 4 个吗 Gotcha

最佳答案

我认为这是预期的行为!
考虑 [1,2], [3,4] 是一个元组文字,等同于元组 ([1,2], [3,4])。 (您可能会在没有注意到的情况下使用它,例如,在使用 a, b, c = 10, 20, 30 分配多个值时忽略 ()...) .

因此在您的示例中,循环按如下方式遍历此列表:

# First iteration we get:
x, y = [1, 2]  
# Which is the same as:
x = 1
y = 2
# Which would print:
print(x, y, x+y)
>> 1, 2, 3

# Second iteration we get:
x, y = [3, 4]  
# Which is the same as:
x = 3
y = 4
# Which would print:
print(x, y, x+y)
>> 3, 4, 7  

现在这样更有意义了吗?


考虑 zip:如果 zip 会做同样的事情,然后我会怀疑!怎么会有这种非常常见且被认为有用但完全多余的东西?没有人注意到吗?所以您不应该期望他们也这样做! ;-)


根据对文档指针的请求进行编辑。
来自 5.3 Tuples and Sequences :

A tuple consists of a number of values separated by commas, for instance: ...
As you see, on output tuples are always enclosed in parentheses, so that nested tuples are interpreted correctly; they may be input with or without surrounding parentheses, although often parentheses are necessary anyway (if the tuple is part of a larger expression).

关于python - 为什么 for 中的逗号分隔迭代不像 zip 那样工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53700572/

相关文章:

python - 如何根据特定的键值对比较两个 pandas 系列?

python - 返回生成器或迭代器生成的所有元素的标准方法

Julia splat 运算符拆包

python - 从下拉列表中的数据库 mysql 中选择条目,python Flask

python - 将稀疏矩阵快速插入另一个矩阵

python-3.x - Pycharm安装Python打包工具失败

scala - 有没有办法从列表创建元组(无需代码生成)?

python - 如何在 Python 2 中正确编码向量化函数条目

python - 让 PostgreSQL 尊重输入参数的顺序?

python-3.x - 如何修复 ‘AttributeError: cffi library ' _constant_time' 在 django 中没有名为 '__spec__' 的函数、常量或全局变量的错误”