[英]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
Try friend in friends
. friend in friends
尝试friend in friends
。 You kinda overwriting friends
with same name of iterator. 您有点用相同的迭代器名称覆盖friends
。
When you write: 当你写:
for friends in friends:
you re-assign the label friends
to the items in this array. 您可以将标签friends
重新分配给该数组中的项目。 After loop completion, the array does not have any name, and hence is lost. 循环完成后,该数组没有任何名称,因此会丢失。 However, the label friends
will store the last value of that array. 但是,标签friends
将存储该数组的最后一个值。 eg ( ->
means ' points to ') 例如( ->
表示' 指向 ')
Before iteration: friends -> array
Ist iteration: friends -> 'Masum'
2nd iteration: friends -> 'Pavel'
3rd iteration and after loop completion: friends -> 'Sohag'
Note that there is only one variable now with value 'Sohag'. 请注意,现在只有一个变量值为“ Sohag”。 Every other variable/array is lost. 其他所有变量/数组均丢失。
Because you used the name friends for the list and for the string, so your variable friends was changed from ['Masum','Pavel','Sohag'] to "Sohag" at the end of your for. 因为您在列表和字符串中使用了名称friends,所以您变量的好友从for末尾的['Masum','Pavel','Sohag']更改为“ Sohag”。
To correct this just change your for to: for friend in friends 要更正此问题,只需将您的for更改为:for friends in friends
Do not use the same variable name as the list for the iteration: 不要将与迭代列表相同的变量名使用:
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.