我是新來的蟒蛇。我正在學習的語法for循環蟒蛇爲:爲什麼for循環在Python中不按預期打印?
for var in list_name:
# do something
我參加了一個清單:
list = [1,2,3,4,5,6,7,8,9]
我要加倍它的每個元素,所以我運行一個循環爲:
for i in list :
index = list.index(i)
list[index] = 2*i
print(list)
然後打印:
[16,2,12,4,10,6,14,8,18]
我不明白爲什麼它是這樣打印的?
爲什麼你要改變循環中循環的列表中的內容?這就像你現在經歷的各種奇怪的事情。在循環外部創建一個空列表並將計算結果附加到循環中,或者使用list comprehension http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions。 –
thanx @Yaw,我曾經在c中做過同樣的事情,那是我在這裏做的... – sdream
說實話,在迭代時修改列表元素根本就不是問題(除非你在一個函數中做,期望列表被修改)。雖然修改列表本身是完全不同的事情(你不想這樣做*)。 – ThiefMaster