2017-10-11 51 views
0
friends = ['Masum','Pavel','Sohag'] 
print(friends[1]) # this one gives me the result 'Pavel' 

for friends in friends: 
    print('Happy new yers,', friends) 

print(friends[1]) # Why this one give me the result o 
+6

因爲你已經使用循環變量'friends'遮蓋了列表'friends' - 你正在獲得''Sohag'[0]'。嘗試'在朋友的朋友:''而不是。 – jonrsharpe

回答

0

因爲你使用名字朋友的名單和字符串,所以你的變量朋友從['Masum','Pavel','Sohag']更改爲「Sohag」。

要糾正這只是更改了到: 的朋友的朋友

0

嘗試friend in friends。你有點覆蓋friends與同名的迭代器。

0

不要使用相同的變量名的列表迭代:

friends = ['Masum','Pavel','Sohag'] 

for friend in friends: 
    print('Happy new yers,', friend) 

# At this point friend will be the last one while friends will still be the list you assigned 
1

當你寫:

for friends in friends: 

重新分配標籤friends在這個項目陣列。 循環完成後,該數組沒有任何名稱,因此丟失。但是,標籤friends將存儲該數組的最後一個值。 例如(->手段「指向」)

Before iteration: friends -> array 
Ist iteration: friends -> 'Masum' 
2nd iteration: friends -> 'Pavel' 
3rd iteration and after loop completion: friends -> 'Sohag' 

注意,只有一個變量現在具有值‘索哈傑’。其他每個變量/數組都會丟失。

相關問題