《Python编程快速上手——让繁琐工作自动化》实践项目——物品清单

题目:

整个题目篇幅比较大。简化一下就是编写addToInventory函数并且返回一个字典。

思路:函数displayInventory用于物品清单的最后输出,而addToInventory是用于处理战利品的,在原来的装备上添加,已有的装备直接数量加1。而没有的添加到自己装备中,并且数量为1,之后再次出现数量直接加1。因此我们可以先用get方法来判断是否有该装备,也就是键,如果有,数量加1,没有就创建键值对{xx:1}。

python 复制代码
def addToInventory(inventory, addedItem):
    for i in addedItem:
        if inventory.get(i, 0) != 0:  # 如果不存在,get会返回备用值0
            inventory[i] += 1

        else:
            inventory.setdefault(i, 1)  # setdefault方法来创建新的键值对 
    return inventory

完整代码以及输出如下:

python 复制代码
def displayInventory(inventory):
    print("Inventory:")
    item_total = 0
    for k, v in inventory.items():
        print(str(v) + ' ' + k)
        item_total += v
    print("Total number of items: " + str(item_total))


def addToInventory(inventory, addedItem):
    for i in addedItem:
        if inventory.get(i, 0) != 0:
            inventory[i] += 1

        else:
            inventory.setdefault(i, 1)
    return inventory


if __name__ == '__main__':
    inv = {'gold coin': 42, 'rope': 1}
    dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
    inv = addToInventory(inv, dragonLoot)
    displayInventory(inv)
python 复制代码
Inventory:
45 gold coin
1 rope
1 dagger
1 ruby
Total number of items: 48
相关推荐
easyboot8 分钟前
C#通过sqlsugar插入数据到postgresql
开发语言·c#
txinyu的博客13 分钟前
C++ 线程库
开发语言·c++
许同13 分钟前
JS-WPS 自动化办公(4)文件管理+超链接
javascript·自动化·wps
木土雨成小小测试员14 分钟前
Python测试开发之后端一
开发语言·数据库·人工智能·python·django·sqlite
superman超哥16 分钟前
Serialize 与 Deserialize Trait:Rust 类型系统与序列化的完美融合
开发语言·rust·开发工具·编程语言·rust序列化·rust类型·serialize
黎子越21 分钟前
python循环相关联系
开发语言·python·算法
安然无虞23 分钟前
「正则表达式」精讲
开发语言·测试工具·正则表达式
csbysj202028 分钟前
DOM 解析器错误
开发语言
Дерек的学习记录32 分钟前
二叉树(下)
c语言·开发语言·数据结构·学习·算法·链表
葡萄成熟时 !35 分钟前
JDK时间类
java·开发语言