當需要存儲很多同類型的不通過數據時可能需要使用到嵌套,先用一個例子說明嵌套的使用
1、在列表中存儲字典
#假設年級里有一群國際化的學生,有黃皮膚的中國人、有白皮膚的美國人也有黑皮膚的非洲人,只記錄部分特征student_1={'nationality':'China','colour':'yellow','age':'15'}student_2={'nationality':'America','colour':'white','age':'18'}student_3={'nationality':'Africa','colour':'dark','age':'17'}grade = [student_1,student_2,student_3]for student in grade:  print(student)輸出:
{‘nationality': ‘China', ‘age': ‘15', ‘colour': ‘yellow'}
{‘nationality': ‘America', ‘age': ‘18', ‘colour': ‘white'}
{‘nationality': ‘Africa', ‘age': ‘17', ‘colour': ‘dark'}
注意,上邊的實例中就將字典作為列表的元素進行了嵌套,然后利用列表進行遍歷
下邊假設年級里有30個同樣年齡的中國學生,利用嵌套進行生成
#定義一個存儲中國學生的列表,假設年齡都一樣chinese=[]#創建30個中國學生for student in range(0,30):  student_1={'nationality':'China','colour':'yellow','age':'15'}  chinese.append(student_1)#顯示一共創建了多少個學生print('一共創建了:'+str(len(chinese))+'個學生')#顯示前5個中國學生for stu in chinese[:5]:  print(stu)輸出:
{‘colour': ‘yellow', ‘age': ‘15', ‘nationality': ‘China'}
{‘colour': ‘yellow', ‘age': ‘15', ‘nationality': ‘China'}
{‘colour': ‘yellow', ‘age': ‘15', ‘nationality': ‘China'}
{‘colour': ‘yellow', ‘age': ‘15', ‘nationality': ‘China'}
{‘colour': ‘yellow', ‘age': ‘15', ‘nationality': ‘China'}
可是這么多學生的年齡都相同,顯得不夠自然,我們將前兩個中國學生改成美國學生、年齡改成14歲
#定義一個存儲中國學生的列表,假設年齡都一樣chinese=[]#創建30個中國學生for student in range(0,30):  student_1={'nationality':'China','colour':'yellow','age':'15'}  chinese.append(student_1)#顯示一共創建了多少個學生print('一共創建了:'+str(len(chinese))+'個學生')for student_c in chinese[0:2]:  if student_c['nationality']=='China':    student_c['nationality']='America'    student_c['colour']='white'    student_c['age']=14#顯示前5個中國學生for stu in chinese[:5]:  print(stu)輸出:
一共創建了:30個學生
{‘colour': ‘white', ‘nationality': ‘America', ‘age': 14}
{‘colour': ‘white', ‘nationality': ‘America', ‘age': 14}
{‘colour': ‘yellow', ‘nationality': ‘China', ‘age': ‘15'}
{‘colour': ‘yellow', ‘nationality': ‘China', ‘age': ‘15'}
{‘colour': ‘yellow', ‘nationality': ‘China', ‘age': ‘15'}
新聞熱點
疑難解答