我只是通過Python文檔教程的循環技巧章去了,我有一個關於這個男孩在這裏一個問題:[:]
爲什麼這是一個永無止境的循環
我瞭解到,它需要的在開始和結束索引字符串,所以:
text = "This is text"
text[:] # will return the whole text "This is text" and
tex[:4] # will return "This".
但是當我看到這裏的代碼...
words = ['cat', 'dog', 'cowcowcow']
for w in words[:]: # Loop over a slice copy of the entire list.
if len(w) > 6:
words.insert(0, w)
print words
輸出:
['cowcowcow', 'cat', 'dog', 'cowcowcow']
...我在for循環中不理解[:]的含義。我只想寫
for w in words:
但是當我這樣做時,它是一個無盡的while循環,爲什麼?
http://stackoverflow.com/questions/6167238/what-does-in-python-mean http://stackoverflow.com/questions/4947762/python-why-use-list-when- list-refer-to-same-thing – 2013-04-22 17:28:03
你的輸出與你的代碼不匹配 - 對於所有的單詞,「len(w)」都是'3'。 – 2013-04-22 17:31:17
你說得對。我剛剛編輯它。 – Johnny 2013-04-22 17:40:20