简体   繁体   English

python 代码未显示所需的 output,问题出在哪里?

[英]The python code isn't showing desired output , where is the problem?

My python code is:我的 python 代码是:

new_alien={'color':'green','points':5,'speed':'slow'}
aliens=[]
for alien_number in range(10):
    aliens.append(new_alien)
print(f"total aliens:{len(aliens)}")
print(".......")
print(aliens)

for alien in aliens[:3]:
    if alien['color']=='green':
        alien['color']='yellow'
        alien['points']=10
        alien['speed']='fast'

print(aliens)

And it is showing output like:它显示 output 像:

total aliens:10
.......
[{'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}]
[{'color': 'yellow', 'points': 10, 'speed': 'fast'}, {'color': 'yellow', 'points': 10, 'speed': 'fast'}, {'color': 'yellow', 'points': 10, 'speed': 'fast'}, {'color': 'yellow', 'points': 10, 'speed': 'fast'}, {'color': 'yellow', 'points': 10, 'speed': 'fast'}, {'color': 'yellow', 'points': 10, 'speed': 'fast'}, {'color': 'yellow', 'points': 10, 'speed': 'fast'}, {'color': 'yellow', 'points': 10, 'speed': 'fast'}, {'color': 'yellow', 'points': 10, 'speed': 'fast'}, {'color': 'yellow', 'points': 10, 'speed': 'fast'}]

Why is it changing all the elements of the list 'alien' though I looped through only the first 3 elements?为什么它会改变列表“外星人”的所有元素,尽管我只遍历了前 3 个元素?

To properly copy dictionaries, you must use the your_dictionary.copy() method, as shown below:要正确复制字典,必须使用your_dictionary.copy()方法,如下所示:

first_dict = {"world":"hello"}
second_dict = first_dict.copy()
second_dict["world"] = "goodbye"    # After doing this, first_dict is still {"world":"hello"}.

It's because all the elements in aliens refer to the same variable new_alien这是因为new_alien中的所有元素都引用同一个变量aliens

Use new_alien.copy()使用new_alien.copy()

new_alien={'color':'green','points':5,'speed':'slow'}
aliens=[]
for alien_number in range(10):
    aliens.append(new_alien.copy())
    
    
print(f"total aliens:{len(aliens)}")
print(".......")
print(aliens)

for alien in aliens[:3]:
    if alien['color']=='green':
        alien['color']='yellow'
        alien['points']=10
        alien['speed']='fast'

print(aliens)

You can solve by moving the alien definition into the for loop.您可以通过将外星人定义移动到 for 循环中来解决。 This will create a new dict in each array entry, rather than all referencing the same thing:这将在每个数组条目中创建一个新的字典,而不是全部引用相同的东西:

aliens=[]
for alien_number in range(10):
    aliens.append({'color':'green','points':5,'speed':'slow'})
print(f"total aliens:{len(aliens)}")
print(".......")
print(aliens)

A tricky one.一个棘手的。

When a dictionary is stored in memory, and unlike a string, any variable pointing it will be the same dictionary.当字典存储在 memory 中时,与字符串不同,指向它的任何变量都将是同一个字典。 Try this:尝试这个:

a = {"foo": "bar"}
b = a
a["foo"] = "surprise!"
print(b)

You must use the.copy method of the dict to have diferent aliens:您必须使用 dict 的 .copy 方法来拥有不同的外星人:

alien.append(new_alien.copy())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM