执行以下代码后x
的值是多少?
x = []
for i in range(3):
x = [x + x]
A.[[[[]]]].
B.[[[],[]]].
C.[[[[],[]],[[],[]]]].
D.[[],[],[],[],[],[]]
答案是 c ,有人可以解释为什么会这样吗?我理解2/3迭代,但不理解它是如何从第1到第2,因为它为什么没有成为[[],[]]
答案 0 :(得分:14)
我使用额外的空格来表达清晰。
首次运行:
x + x = [] + [] = []
空列表+空列表是另一个空列表
所以[x + x] = [ [] ]
注意! [[]]
不是空列表,它是包含空列表的列表
第二次运行:
x + x = [[]] + [[]] = [[], []]
所以[x + x] = [ [[], []] ]
第三次运行:
x + x = [[[], []]] + [[[], []]] = [[[[], []]], [[[], []]]]
所以[x + x] = [ [[[[], []]], [[[], []]]] ]
答案 1 :(得分:8)
x = []
for i in range(3):
print('\ni =', i)
print('x =' , x)
print('x + x =', x + x)
print('[x + x] =', [x + x])
x = [x + x]
<强>输出:强>
i = 0
x = []
x + x = [] # Here is why. If you extend [] by [], you get [].
[x + x] = [[]] # And we wrap the result.
i = 1
x = [[]]
x + x = [[], []]
[x + x] = [[[], []]]
i = 2
x = [[[], []]]
x + x = [[[], []], [[], []]]
[x + x] = [[[[], []], [[], []]]]
答案 2 :(得分:3)
让我们逐步完成代码,是吗?:
x = []
:创建一个名为x
for i in range(3)
:重复以下代码三次:
x = [x + x]
将x
的值重新分配给x
的当前值,加上x
的当前值并将其包装在列表中。基本上,每次迭代发生的事情是您的列表嵌套在一个级别,列表中的列表当前成为该嵌套列表的子列表。
用外行人的话来说,最简单的解释是 - 在for循环的每次迭代中,变量x的值被重新赋值为两个嵌套的值,其中还可以包含两个嵌套列表,单一列表。
以下是在for
- 循环的每次迭代中显示x值的说明:
>>> # x is empty
>>> x = []
>>>
>>> # 1st iteration
>>> x = [x + x]
>>> # x
>>> x
[[]] # your list is nested by one level
>>>
>>> # 2nd iteration
>>> x = [x + x]
>>> # x
>>> x
[[[], []]] # your list is nested by three levels
>>> # 3rd iteration
>>> x = [x + x]
>>> # x
>>> x
[[[[], []], [[], []]]] # your list is nested by four levels
>>>
如果上面的插图过于拥挤,请选择较短的插图:
First iteration
Value of x: [[]]
Second iteration
Value of x: [[[], []]]
Third iteration
Value of x: [[[[], []], [[], []]]]
我还发现从嵌套列表中创建一个类似树的结构,有助于更好地理解发生的事情:
[ # 1st level
[ # second level
[ # third level
[], # fourth level
[]
],
[
[],
[] # fourth level
] # third level
] # second level
] # 1st level