笔记出处(学习UP主视频记录) https://www.bilibili.com/video/av35698354?p=13
6.4 嵌套
6.4.1 字典列表
alien_0 = {'color': 'green', 'points': 5} alien_1 = {'color': 'yellow', 'points': 10} alien_2 = {'color': 'red', 'points': 15} aliens = [alien_0, alien_1, alien_2] for alien in aliens: print(alien)
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}
# 创建一个外星人空列表 aliens = [] #创建30个绿色的外星人 for alien_number in range(30): new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'} aliens.append(new_alien) #显示前5个外星人 for alien in aliens[:5]: print(alien) print('...') # 显示创建了多少个外星人 print("Total number of aliens: " + str(len(aliens)))
{'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'}
...
Total number of aliens: 30
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 for alien in aliens[:5]: print(alien) print("...") 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': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
...
Total number of aliens: 30
6.4.2 在字典中存储列表
pizza = { 'cruse': 'thick', 'toppings': ['mushrooms', 'extra cheese'], } print("You ordered a " + pizza['cruse'] + "-crust pizza" + "with the following toppings:") for topping in pizza['toppings']: print(" " + topping)
You ordered a thick-crust pizzawith the following toppings:
mushrooms
extra cheese
未写完......