Skip to main content
 首页 » 编程设计

python之为什么我的列表不会遍历每个列表

2025年05月04日15tuyile006

目前正在学习教程“Python the hard way”。

我正在学习列表和循环 (ex32)。

在练习结束时,Zed(教程作者)告诉我们玩一玩,我已经做了。

# we can also build lists, first start with an empty one 
elements = [] 
elements.append(range(0,6)) 
 
# then use the range function to do 0 to 5 counts 
for element in elements: 
    print "Adding %s to elements" % element 
 
 
# now we can print them out too 
for element in elements: 
    print"Element was: %s" % element 

这会产生如下输出:

Adding [0, 1, 2, 3, 4, 5] to elements 
Element was: [0, 1, 2, 3, 4, 5] 

我原以为会看到这样的东西:

Adding 0 to elements 
Adding 1 to elements 
Adding 2 to elements 
Adding 3 to elements 
Adding 4 to elements 
Adding 5 to elements 
Element was: 0 
Element was: 1 
Element was: 2 
Element was: 3 
Element was: 4 
Element was: 5 

但是 Python 想要打印出我的脚本,而不是每个列表组件的连接字符串。

我知道我可以更改脚本以准确反射(reflect)作者的脚本

# we can also build lists, first start with an empty one 
elements = [] 
 
# then use the range function to do 0 to 5 counts 
for i in range(0, 6): 
    print "Adding %d to the list." % i 
    # append is a function that lists understand 
    elements.append(i) 
 
# now we can print them out too 
for i in elements: 
    print "Element was: %d" % i 

但我只想知道为什么我的作品没有按预期工作?

请您参考如下方法:

您正在将列表附加到列表!您只想创建列表!

您只需更改以下内容:

elements = [] 
elements.append(range(0,6)) 

进入

elements = range(0,6) 

你会得到你想要的结果

为什么

当您第一次创建 elements 时,它是一个空白列表。然后将 range(0,6) 附加到空列表中。现在元素看起来像 [[0,1,2,3,4,5]](或 [range(0,6)]),这是一个列表一个元素,一个列表。