python - python "know"如何处理 "in"关键字?

标签 python

我对python中的“in”关键字有点困惑。

如果我采用元组的示例列表:

data = [
    (5, 1, 9.8385465),
    (10, 1, 8.2087544),
    (15, 1, 7.8788187),
    (20, 1, 7.5751283)
]

我可以做两个不同的“for - in”循环并得到不同的结果:

for G,W,V in data:
    print G,W,V

这会在一行上打印每组值,例如5、1、9.8385465

for i in data:
    print i

这会打印整个元组,例如(5, 1, 9.8385465)

python如何“知道”通过提供一个变量我想将元组分配给一个变量,以及通过提供三个变量我想将元组中的每个值分配给其中一个变量?

最佳答案

根据the for compound statement documentation :

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

那些“标准规则”the assignment statement 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.

因此,这种不同的行为,取决于您是分配给单个目标还是目标列表,直接融入 Python 的基础知识,并适用于使用分配的任何地方。

关于python - python "know"如何处理 "in"关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31796910/

相关文章:

python - 如何恢复对 python 包所做的更改?

python - 如何将 DatetimeIndexResampler 转换为 DataFrame?

python - 链接到 Flask 模板中的特定位置

python - 如何使用 Pandas 将数据从一行移动到另一行

python - 对数组的各个列进行排序

python - Pyside 客户端和服务器

python - Python 中的十六进制格式

python - Django 错误 : 'unicode' object is not callable

python - Cython:如何按另一个 vector 对一个 vector 的内容进行排序?

python - 如何为 Keras 实现 KL 散度正则化?