目前正在通過教程「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將整個元素(完整列表)顯示在一個 –