Python学习笔记函数之嵌套的字典和列表

随笔记录方便自己和同路人查阅。

#------------------------------------------------我是可耻的分割线-------------------------------------------

  对于上一章列举的井字棋建模相当简单:棋盘只需要一个字典,包括9个键值对。当你对复杂的事物建模时,

可能发现字典和列表中需要包含其他字典和列表。列表适用于包含一组有序的值,字典适合于包含关联的键于值。

例如,下面的程序使用字典包含其他字典,用于记录谁为野餐带来了什么食物。tatalBrought()函数可以读取这个

数据结构,计算所有客人带来的事物的总数。

#------------------------------------------------我是可耻的分割线-------------------------------------------

  请看以下示例代码:

#
# -*- coding:utf-8 -*-
# Autor: Li Rong Yang
#定义一个字典
allGuests = {'Alice':{'apples':5,'pretzels':12},
             'Bob':{'ham sandwiches':3,'apples':2},
             'Carol':{'cups':3,'apples':1}}
#定义一个函数接收传入的字典和要统计的东西名称
def totalBrought(guests,item):
    numBrought = 0#计数
    for k,v in guests.items():#循环字典的键值对分别放入k,v中
        numBrought = numBrought + v.get(item,0)#检查要统计的物品是否在子字典中,并把该子字典的值给numBrought
    return numBrought#返回该值
print('Number of things being brought:')#提示信息
print(' - Apples ' + str(totalBrought(allGuests, 'apples')))#统计apples
print(' - Cups ' + str(totalBrought(allGuests, 'cups')))#cups
print(' - Cakes ' + str(totalBrought(allGuests, 'cakes')))#cakes
print(' - Ham Sandwiches ' + str(totalBrought(allGuests, 'ham sandwiches')))#统计ham sandwiches
print(' - Apple Pies ' + str(totalBrought(allGuests, 'apple pies')))#统计apple pies

  运行结果:

原文地址:https://www.cnblogs.com/lirongyang/p/9550883.html