Python——for循环——理解

Python - for loop - understanding

我在 python 脚本中遇到 for 循环问题。 问题同时解决了,但我不明白逗号解决问题的必要性。

this was the faulty for loop:

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

result:

Traceback (most recent call last):
File "", line 1, in
ValueError: too many values to unpack (expected 2)


this repaired the faulty for-loop:

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

result:

abc.com ['', 'test']

为什么右括号前需要这个 逗号? 如果我扩展变量内的内容,最后就不需要 逗号

without comma at the end:

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

result:

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


with comma at the end:

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

result:

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

知道为什么有时需要最后一个 逗号 有时不需要吗?

谢谢

第一个例子中 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