Python - for loop - 了解

问题描述 投票:0回答:1

我在一个python脚本中遇到了一个for循环的问题。这个问题已经解决了,但我不明白为什么需要用 逗号 这就解决了这个问题。

这是错误的for循环。

variable= (["abc.com", ["", "test"]]) for a,b in variable: print(a,b)

结果:

回溯(最近一次调用)。 文件"",第1行,在ValueError: 太多的值需要解包(预期2)。


这修复了故障的for-loop。

variable= (["abc.com", ["", "test"]],) for a,b in variable: print(a,b)

结果:

abc.com ['', 'test']

为什么会这样?逗号 如果我在变量内部扩展内容,就不会有 逗号 最后的必要。

而不 逗号 在最后。

variable= (["abc.com", ["", "test"]], ["xyz.com", ["", "test2"]]) for a,b in variable: print(a,b)

结果:

abc.com ['', 'test'] xyz.com ['', 'test2']


逗号 在最后。

variable= (["abc.com", ["", "test"]], ["xyz.com", ["", "test2"]],) for a,b in variable: print(a,b)

结果:

abc.com ['', 'test'] xyz.com ['', 'test2']

知道为什么有时会出现最后的 逗号 有必要,有时又不需要?

谅谅

for-loop python-3.7
1个回答
2
投票

的赋值 variable 在你的第一个例子中,相当于

variable = ["abc.com", ["", "test"]]

即,该值将是一个单一的列表;外层的括号是多余的。当你在上面循环时,第一项是字符串 "abc.com",这将不符合 a, b - 有太多的字母。通过在列表后添加逗号,你可以将表达式变成一个元组。如果你有多个元素,那里已经有一个逗号(在第一个元素之后),所以你不需要再加一个。

启示是。圆括号不能组成元组,逗号才可以! 考虑以下作业

x = 1   # Integer
x = (1) # Also integer
x = 1,  # One-element tuple
x = (1,) # Also one-element tuple
x = 1,2  # Two-element tuple
© www.soinside.com 2019 - 2024. All rights reserved.