python for循环作用域问题
想实现更改aliens列表前面两个字典子元素的值,如下代码会导致所有字典子元素的值都改变。请问是为什么?aliens=[]alien={'speed':'slow','c...
想实现更改aliens列表前面两个字典子元素的值,如下代码会导致所有字典子元素的值都改变。请问是为什么?
aliens = []
alien = {'speed':'slow','color':'green','points':5}
for aliens_number in range(20):
aliens.append(alien)
for x in aliens[0:2]:
if x['color'] == 'green':
x['speed'] = 'medium'
x['color'] = 'yellow'
x['points'] = 15
print aliens
aliens = []
for aliens_number in range(20):
alien = {'speed':'slow','color':'green','points':5} aliens.append(alien) #放到这里就会成功实现
for x in aliens[0:2]:
if x['color'] == 'green':
x['speed'] = 'medium'
x['color'] = 'yellow'
x['points'] = 15
print aliens 展开
aliens = []
alien = {'speed':'slow','color':'green','points':5}
for aliens_number in range(20):
aliens.append(alien)
for x in aliens[0:2]:
if x['color'] == 'green':
x['speed'] = 'medium'
x['color'] = 'yellow'
x['points'] = 15
print aliens
aliens = []
for aliens_number in range(20):
alien = {'speed':'slow','color':'green','points':5} aliens.append(alien) #放到这里就会成功实现
for x in aliens[0:2]:
if x['color'] == 'green':
x['speed'] = 'medium'
x['color'] = 'yellow'
x['points'] = 15
print aliens 展开
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询