![](/img/trans.png)
[英]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.