for循环变量声明中括号的行为
在Python的for循环中,使用括号对变量声明有没有影响呢?
例子1:基本的for循环,声明了一个没有括号的变量i
>>> for i in range(0,10): print(i)
...
0
1
2
3
4
5
6
7
8
9
基本的for循环,声明了一个带有任意括号的变量i
for (((((i))))) in range(0,10): print(i)
...
0
1
2
3
4
5
6
7
8
9
一个for循环,解包两个值,声明时没有使用括号
>>> for x,y in zip(range(0,10), range(0,10)): print(x,y)
...
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
同样的情况,但在x和y周围加了括号,还有两个值都加了括号。
>>> for ((x),(y)) in zip(range(0,10), range(0,10)): print(x,y)
...
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
看起来括号没有什么影响——它们并不会被解释成比如说一个元组。我说得对吗?或者在for循环的变量声明中,有没有理由使用括号呢?
你甚至可以这样写:
>>> for [x,y] in zip(range(0,10), range(0,10)): print(x,y)
...
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
...而且列表的表示法(方括号)似乎也没有什么影响。
3 个回答
2
除了空元组 ()
以外,元组的定义并不是靠括号,而是靠逗号。括号只是用来把元组里的项目和其他代码分开,让它们看起来更清晰。
# These are all identical: x is a tuple with 2 elements.
x = (1, 2)
(x) = (1, 2)
x = 1, 2
(x) = 1, 2
# These are all identical: x is assigned the first element of the tuple (1, 2)
x, = (1, 2)
(x,) = (1, 2)
x, = 1, 2
(x,) = 1, 2
5
仅仅在一个表达式周围加上括号,只是为了把这个表达式分组(比如为了改变运算符的优先级,或者让表达式可以跨多行书写等等)。
如果你想创建元组,就要用逗号:
>>> 1
1
>>> 1,
(1,)
2
在for循环的变量声明中使用括号有什么必要吗?
有的,使用括号可以帮助你处理更复杂的可迭代对象。特别是像这样的嵌套可迭代对象:
enumerate(zip(range(10), range(10, 20)))
使用括号,一切都能正常工作:
>>> for x, (y, z) in enumerate(zip(range(10), range(10, 20))):
... print("x=", x, "y=", y, "z=", z)
...
x= 0 y= 0 z= 10
x= 1 y= 1 z= 11
x= 2 y= 2 z= 12
x= 3 y= 3 z= 13
x= 4 y= 4 z= 14
x= 5 y= 5 z= 15
x= 6 y= 6 z= 16
x= 7 y= 7 z= 17
x= 8 y= 8 z= 18
x= 9 y= 9 z= 19
>>>
因为 x, (y, z)
这个结构和下面返回的可迭代对象的结构是匹配的:
enumerate(zip(range(10), range(10, 20)))
但是如果没有括号,你会遇到 ValueError
错误:
>>> for x, y, z in enumerate(zip(range(10), range(10, 20))):
... print("x=", x, "y=", y, "z=", z)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: need more than 2 values to unpack
>>>
因为Python看到的是 x, y, z
,所以它期望:
enumerate(zip(range(10), range(10, 20)))
返回三个元素的可迭代对象,但实际上只返回了两个元素的(一个数字和另一个包含两个元素的元组):
>>> for item in enumerate(zip(range(10), range(10, 20))):
... print(item)
...
(0, (0, 10))
(1, (1, 11))
(2, (2, 12))
(3, (3, 13))
(4, (4, 14))
(5, (5, 15))
(6, (6, 16))
(7, (7, 17))
(8, (8, 18))
(9, (9, 19))
>>>