2014-02-09 73 views
0

我是新來的蟒蛇。我正在學習的語法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] 

我不明白爲什麼它是這樣打印的?

+1

爲什麼你要改變循環中循環的列表中的內容?這就像你現在經歷的各種奇怪的事情。在循環外部創建一個空列表並將計算結果附加到循環中,或者使用list comprehension http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions。 –

+0

thanx @Yaw,我曾經在c中做過同樣的事情,那是我在這裏做的... – sdream

+0

說實話,在迭代時修改列表元素根本就不是問題(除非你在一個函數中做,期望列表被修改)。雖然修改列表本身是完全不同的事情(你不想這樣做*)。 – ThiefMaster

回答

6

讓我們通過你的循環中的第幾個迭代運行。

迭代1:i是1

index = list.index(i) 
list[index] = 2*i 

index是0,並且list[0]設置爲2*i。該列表現在看起來像[2, 2, 3, 4, 5, 6, 7, 8, 9]

迭代2:i是2。

index = list.index(i) 

list.index(2)發現的2在列表中的第一次出現,是在指數!有多個2,你沒有選擇正確的。

list[index] = 2*i 

你加倍錯了!

這對迭代4,6再次發生,和8


如果你想一個列表的元素翻一番,最簡單的方法是讓一個新的列表與列表理解:

l = [2*i for i in l] 

如果您需要在for循環中元素的索引,最好的解決方法通常是enumerate名單:

for i, item in enumerate(l): 
    whatever() 

此外,不要打電話給您的列表list,或者當您嘗試調用list函數時,您會看到一個奇怪的TypeError。

+0

thanx @ user2357112 – sdream

2

list.index(i)返回列表中找到第一個索引i

thelist = [1,2,3,4,5,6,7,8,9] 

> index = thelist.index(1) 
> index = 0 
> thelist[0] = 2 

> index = thelist.index(2) 
> index = 0 
> thelist[0] = 2*2 = 4 

> index = thelist.index(3) 
> index = 2 
> thelist[2] = 2*3 = 6 

> index = thelist.index(4) 
> index = 0 
> thelist[0] = 2*4 = 8 

> index = thelist.index(5) 
> index = 4 
> thelist[4] = 2*5 = 10 

> index = thelist.index(6) 
> index = 2 
> thelist[2] = 2*6 = 12 

> index = thelist.index(7) 
> index = 6 
> thelist[6] = 2*7 = 14 

> index = thelist.index(8) 
> index = 0 
> thelist[0] = 2*8 = 16 

> index = thelist.index(9) 
> index = 8 
> thelist[8] = 2*9 = 18 

其餘的元素將保持不變。 另外,將關鍵字用作變量名是不正確的。您不應該使用list作爲變量名稱。

+1

+1爲了完整,還包括一個工作版本。 –

0

因爲您每次都在更改列表的錯誤元素。語法for i in list設置列表中的一個元素的值,而不是索引。

事實上,你不應該改變你正在處理的列表,而是要創建一個新列表。正確的方法是:如你預期

new_list = [] 
for i in list: 
    new_list.append(2*i) 

# Or even, with a list comprehension 
new_list = [i*2 for i in list] 

print(new_list) 
3

您的代碼不起作用,因爲list.index將返回列表中的元素的第一指標。因此,如果同一個元素出現多次,它將無法按預期工作。

翻番元素的最好方法是使用列表理解,這樣

my_list = [item * 2 for item in my_list] 

如果你想使用一個for循環,您可以使用enumerate,這樣

for index, current_num in enumerate(my_list): 
    my_list[index] = current_num * 2 

這是醜,因爲我們在迭代它時正在修改列表。所以,不要這樣做。相反,你可以像這樣

for index in xrange(len(my_list)): 
    my_list[index] *= 2 
+0

迭代時,您不能更改列表的**長度**,但更改元素完全正常。 –

+0

@JochenRitzel請檢查[this](http://ideone.com/TysdVY) – thefourtheye

0
print map(lambda x: x*2, my_list) 
+0

明顯地打印他想要的東西,但它不回答他的問題:「我不明白它爲什麼打印這樣?和「爲什麼循環不按照預期在Python中打印?」。 – Dirk

+0

正確。我沒有試圖回答這些問題,因爲我們已經有了更好更全面的答案。一想到他明白自己做錯了什麼,並尋找其他方法來實現「他想要的」,他可能會發現它很有用。 – idanshmu