我不明白为什么

2024-09-28 13:13:30 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么代码中的这一点变化会使代码的工作方式有所不同。我只是在学Python。有人能简单地解释一下吗? 编辑: 我没有意识到在列表中附加字典是指向同一本字典,而不是它的实际副本。在这篇文章之前,我试图在这里找到解决方案,但我的问题可能有点不同,这可能会导致经验丰富的程序员将其视为重复。你知道吗

输入

# Make an empty list for storing aliens.
aliens = []
# Make 30 green aliens.
for alien_number in range(30):
    new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
    aliens.append(new_alien)

for alien in aliens[0:3]:
    if alien['color'] == 'green':
        alien['color'] = 'yellow'
        alien['speed'] = 'medium'
        alien['points'] = 10
# Show the first 5 aliens:
for alien in aliens[:5]:
    print(alien)
print("...")
# Show how many aliens have been created.
print("Total number of aliens: " + str(len(aliens)))

输出

{'points': 10, 'color': 'yellow', 'speed': 'medium'}
{'points': 10, 'color': 'yellow', 'speed': 'medium'}
{'points': 10, 'color': 'yellow', 'speed': 'medium'}
{'points': 5, 'color': 'green', 'speed': 'slow'}
{'points': 5, 'color': 'green', 'speed': 'slow'}
...
Total number of aliens: 30

现在更改了代码,我将在第一个for循环外初始化dictionary

输入

# Make an empty list for storing aliens.
aliens = []
# HERE IS THE CHANGE
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
# Make 30 green aliens.
for alien_number in range(30):
    aliens.append(new_alien)

for alien in aliens[0:3]:
    if alien['color'] == 'green':
        alien['color'] = 'yellow'
        alien['speed'] = 'medium'
        alien['points'] = 10
# Show the first 5 aliens:
for alien in aliens[:5]:
    print(alien)
print("...")
# Show how many aliens have been created.
print("Total number of aliens: " + str(len(aliens)))

输出

{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}   
...
Total number of aliens: 30

为什么在第二个是整个字典的变化,而不仅仅是前3个词汇?你知道吗


Tags: innumbernewformakegreenpointscolor
1条回答
网友
1楼 · 发布于 2024-09-28 13:13:30

代码的要点是,当您构建第一个字典时,它会创建它并将对它的引用存储在new_alien变量中。请注意,这不是对象本身,而是对对象的引用。 在第一个代码段中,您每次都创建了一个新字典,并将对新字典的引用附加到aliens列表中。在第二种情况下,您只创建了一个字典,并在列表中添加了五次对同一个字典的引用。 这就解释了为什么在第二种情况下,你实际上是在修改同一本词典。让我们看看这个例子:

dct = {'a': 10, 'b': 20}  # in this moment the dictionary is initialised and a reference to it is stored in the variable dct (let's call this reference 0x01)
# dct = 0x01
lst = []
for i in range(5):
    lst.append(dct)
# at the end of the loop lst = [0x01, 0x01, 0x01, 0x01, 0x01]
lst[0]['a'] = 20  # this means take lst[0] (which is 0x01) interpret it as a dictionary and change the value at `'a'` to 20

因此,这个更改将影响您创建的唯一字典,即dct。 在您的第一个代码段中,您创建了5个不同的字典,只修改了其中的一部分,请参见以下示例:

lst = []
for i in range(5):
    new_dict = {'a': 10, 'b': 20}
    lst.append(new_dict)
# by the end of the loop, lst will have references to five different dictionaries, for instance lst = [0x01, 0x02, 0x03, 0x04, 0x05]

因此在这种情况下,修改其中一个条目不会影响其他条目

相关问题 更多 >

    热门问题