Python 未捕获的 List 变量的行为 [英] Python uncaught List variable's behavior
问题描述
谁能解释一下我得到的输出.第一次变量 lists
为空,但是当 data[i]
即 10
附加到 lists[i]代码>变成
Can anyone please explain the output i am getting. As the first time the variable lists
is blank but when data[i]
i.e 10
appended to the lists[i]
it becomes
List: [[10], [10, [10]]
我不知道这个长列表是怎么来的.我是 python 的新手,可以跟踪它的行为.这是代码
I dont know how come this long list comes in. I am new to python struck to trace its behavior. Here is the code
data = [10, 20, 30]
list1 = list2 = list3 = list()
lists = [list1, list2, list3]
for i in range(len(data)):
lists[i].append(data[i])
print '-------------------'
print 'at %s' %(i)
print ' List: %s' % (lists)
print ' Data: %s' % (data[i])
和回应
-------------------
at 0
List: [[10], [10], [10]]
Data: 10
-------------------
at 1
List: [[10, 20], [10, 20], [10, 20]]
Data: 20
-------------------
at 2
List: [[10, 20, 30], [10, 20, 30], [10, 20, 30]]
Data: 30
推荐答案
This is an invalid question(它包含其他代码的输出然后提供),您可能正在运行第二个(初始化后)在你的口译员中多次参与.你的代码输出应该是这样的
This is an invalid question (it contains output of other code then provided), you are probably running the second (after initialization) part multiple times in your interpreter. The output of your code should look like
-------------------
at 0
List: [[10], [10], [10]]
Data: 10
-------------------
at 1
List: [[10, 20], [10, 20], [10, 20]]
Data: 20
-------------------
at 2
List: [[10, 20, 30], [10, 20, 30], [10, 20, 30]]
Data: 30
在 Python 2.7 上测试
tested on Python 2.7
这个问题 所以我不会重复这些信息.
The aspect of "multiple additions" has been already answered in this question so I do not duplicate this information.
这篇关于Python 未捕获的 List 变量的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!