我对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/