嵌套
(有时候,我们需要将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套。嵌套可以是,列表中嵌套字典,在字典中嵌套列表,在字典中嵌套字典,可以在列表中嵌套列表吗?)
#例子1
(列表中存储三个不同颜色的外星人)
alien_1={'color':'green','points':5}
alien_2={'color':'red','points':10}
alien_3={'color':'blue','points':-5}
alien_list=[alien_1,alien_2,alien_3]
print(alien_list)
运行结果:
[
{'color': 'green', 'points': 5},
{'color': 'red', 'points': 10},
{'color': 'blue', 'points': -5}
]
#例子2
(用range()函数批量创建外星人)
alien_list=[]
for alien in range(11):
alien={'color':'green','points':5}
alien_list.append(alien)
print('这里创建了'+str(len(alien_list))+'个外星人')
运行结果:
这里创建了11个外星人