python中的嵌套

博客 动态
0 208
优雅殿下
优雅殿下 2022-04-13 17:57:55
悬赏:0 积分 收藏

python中的嵌套

嵌套:将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套。既可以在列表中嵌套字典,也可以在字典中嵌套列表,甚至在字典中嵌套字典。

一、列表中嵌套字典 

1)一般创建方式:

student_A ={'name':'Allen','age':'14','grade':'8'} student_B ={'name':'Jack','age':'12','grade':'6'} student_C ={'name':'Lucy','age':'13','grade':'7'} student_D ={'name':'polo','age':'14','grade':'8'} #上述四行,创建了4个字典,每个字典代表一个学生students=[student_A,student_B,student_C,student_D]#将上述4个学生放名为students的列表中for student in students:  #遍历students列表    print(student)        #打印每个学生print("\n")  

 2)批量创建同类型的字典,比如游戏中很多同类型小兵

#创建更多的同类型的字典ghosts=[]      #创建一个空ghosts列表for ghost_number in range(10):  #创建10个ghost,注意range(10)是从0-9    new_ghost={'name':'rubbish','life':'10','speed':'1'}    #同类型的名字rubbish,颜色为green,生命力为10,速度为1    ghosts.append(new_ghost)   #append()是将创建的new_ghost放到列表ghosts最后    for ghost in ghosts:   #遍历创建的ghosts列表    print(ghost)   #打印ghosts中的每个元素,即10个同类型的ghost    print("Total number of ghosts:"+str(len(ghosts)))    #打印ghosts列表中元素的个数,len()求元素个数,str()转为字符串

 3)同类型的字典,可通过循环,及切片进行增、删、改等操作。

for ghost in ghosts[0:3]:     if ghost['color'] == 'green':        ghost['color'] = 'yellow'        ghost['speed'] = 2        ghost['life'] = 5for ghost in ghosts:       print(ghost)    

运行如果:

 二、字典中嵌套列表

比如在实际生活中,描述菜单,如果使用列表,只能存储菜肴的配料;但如果使用字典,就不仅可在其中包含配料列表,还可包含其他有关描述。
如下示例,存储了菜单的两方面信息:菜肴类型和配料列表。
其中的配料列表是一个与键 'toppings' (佐料)相关联的值。
要访问该列表,使用字典名和键 'toppings' ,就像访问字典中的其他值一样,这将返回一个配料列表,而不是单个值

1)嵌套一个列表

# 存储所点菜单的信息menu = {  # 定义一个菜单字典'style': 'sichuan',   #定义菜单的类型,四川菜'toppings': ['salt', 'sugar','vinegar','Sichuan Pepper']  # 定义一个佐料的列表,包含盐、糖、醋、花椒}   #存储了有关顾客所点菜肴的信息# 概述所点的菜单print("You ordered a " + menu['style'] + "-style menu " +"with the following toppings:")  for topping in menu['toppings']:          print("\t" + topping)

2)嵌套多个列表

favor_languages = {'jack': ['python', 'ruby'],'sarah': ['c','C++'],'edward': ['ruby', 'go'],'polo':['c#','java']}for name, languages in favor_languages.items():     print("\n" + name.title() + "'s favorite languages are:")    for language in languages:        print("\t" + language.title())     

 

三、在字典中存储字典

网站有多个用户,每个都有独特ID(或用户名),可以在字典中将用户名作为键,再将每位用户的信息存储在一个字典中,并将该字典作为与用户名相关联的值。对于每位用户,都存储了其三项信息:名、姓和居住地;为访问这些信息,遍历所有的用户名,并访问与每个用户名相关联的信息字典

#在字典中嵌套字典users = {    #创建一个users的字典,字典中有两个关键字(id)lucyb和merryb,'lucyb': {'firstname': 'lucy','lastname':'Bush','location': 'califorlia'},'merryb':{'firstname':'merry','lastname':'Biden','location':'San Francisco'}}  # lucyb和merryb又分别为两字典,各自有三个关键字,firstname,lastname和locationfor username, user_info in users.items():  #遍历字典uers的每一项    print("\nUsername: " + username)     full_name = user_info['firstname'] + " " + user_info['lastname']    location = user_info['location']    print("\tFull name: " + full_name.title())    print("\tLocation: " + location.title())  

运行结果:

 

posted @ 2022-04-13 17:30 PursuitingPeak 阅读(0) 评论(0) 编辑 收藏 举报
回帖
    优雅殿下

    优雅殿下 (王者 段位)

    2018 积分 (2)粉丝 (47)源码

    小小码农,大大世界

     

    温馨提示

    亦奇源码

    最新会员