[英]Why do the same operations on numpy and python list get different results?
[英]list python; why get different results?
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
friend in friends
嘗試friend in friends
。 您有點用相同的迭代器名稱覆蓋friends
。
當你寫:
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'
請注意,現在只有一個變量值為“ Sohag”。 其他所有變量/數組均丟失。
因為您在列表和字符串中使用了名稱friends,所以您變量的好友從for末尾的['Masum','Pavel','Sohag']更改為“ Sohag”。
要更正此問題,只需將您的for更改為:for friends in friends
不要將與迭代列表相同的變量名使用:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.