简体   繁体   English

列出python; 为什么会得到不同的结果?

[英]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.

相关问题 为什么对numpy和python list进行相同的操作会得到不同的结果? - Why do the same operations on numpy and python list get different results? Python 多处理和共享 memory - 为什么我得到不同的结果? - Python multiprocessing and shared memory - why do I get different results? 为什么在 Python 中使用相同的代码会得到不同的结果? - Why do I get different results with the same code in Python? 为什么我用这两组Python代码得到不同的结果 - Why do I get different results with these two sets of Python Code python`list`和`for`返回不同的结果 - python `list` and `for` return different results 为什么我得到不同的结果 - why I get different results 为什么在递归问题中使用 list.pop() 和 list = list[:-1] 时得到不同的结果 - Why get different results, when using list.pop() and list = list[:-1] in recursive problem 为什么用 list 操作会给出不同的结果? - Why operating with list gives different results? 为什么map()和列表理解的结果不同? - Why results of map() and list comprehension are different? python CNN,为什么我在不同的桌面上得到不同的结果?我该怎么做才能在不同的机器上得到相同的结果 - python CNN,why i get different results in different desktop?what can i do to get the same result in different machine
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM