首页 > 编程 > 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'}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表