国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python使用字典的嵌套功能詳解

2020-02-16 01:22:56
字體:
來源:轉載
供稿:網友

當需要存儲很多同類型的不通過數據時可能需要使用到嵌套,先用一個例子說明嵌套的使用

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'}

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 延长县| 上蔡县| 潼关县| 阳西县| 平武县| 曲麻莱县| 阳东县| 龙陵县| 泽库县| 临清市| 洪湖市| 延长县| 靖西县| 高碑店市| 富锦市| 镇赉县| 榆社县| 文化| 丹棱县| 常德市| 双江| 新兴县| 泌阳县| 新邵县| 石棉县| 澄江县| 清苑县| 南投市| 唐海县| 乌拉特中旗| 井冈山市| 石嘴山市| 宁蒗| 定西市| 黔江区| 成安县| 阿荣旗| 南汇区| 拉孜县| 都安| 南江县|