list python;为什么得到不同的结果
问题描述:
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
答
因为你使用名字朋友的名单和字符串,所以你的变量朋友从['Masum','Pavel','Sohag']更改为“Sohag”。
要纠正这只是更改了到: 的朋友的朋友
答
尝试friend in friends
。你有点覆盖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
答
当你写:
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'
注意,只有一个变量现在具有值‘索哈杰’。其他每个变量/数组都会丢失。
因为你已经使用循环变量'friends'遮盖了列表'friends' - 你正在获得''Sohag'[0]'。尝试'在朋友的朋友:''而不是。 – jonrsharpe