为什么代码中的这一点变化会使代码的工作方式有所不同。我只是在学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个词汇?你知道吗
代码的要点是,当您构建第一个字典时,它会创建它并将对它的引用存储在
new_alien
变量中。请注意,这不是对象本身,而是对对象的引用。 在第一个代码段中,您每次都创建了一个新字典,并将对新字典的引用附加到aliens
列表中。在第二种情况下,您只创建了一个字典,并在列表中添加了五次对同一个字典的引用。 这就解释了为什么在第二种情况下,你实际上是在修改同一本词典。让我们看看这个例子:因此,这个更改将影响您创建的唯一字典,即
dct
。 在您的第一个代码段中,您创建了5个不同的字典,只修改了其中的一部分,请参见以下示例:因此在这种情况下,修改其中一个条目不会影响其他条目
相关问题 更多 >
编程相关推荐