目前正在通过教程“Python艰难的方式”。为什么我的列表不会遍历每个列表?
我在学习列表和循环(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希望在oner打印出我的剧本,而而不是每个列表组件连接的字符串。
我知道,我可以改变剧本,以反映作者脚本正是
# 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 = range(0,6)'并不能真正帮助你:) –
感谢你的回答。你的开放使它点击了“你将一个列表追加到列表中”,所以Python将整个元素(完整列表)显示在一个 –