《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
相关推荐
几何心凉6 分钟前
AI时代结合Haystack实现自定义数据抓取工具
开发语言
小鸡吃米…8 分钟前
TensorFlow 实现异或(XOR)运算
人工智能·python·tensorflow·neo4j
深蓝电商API16 分钟前
Redis 作为爬虫去重与任务队列实战
爬虫·python
csbysj202018 分钟前
JSP 文件上传详解
开发语言
郝学胜-神的一滴21 分钟前
FastAPI:Python 高性能 Web 框架的优雅之选
开发语言·前端·数据结构·python·算法·fastapi
柒.梧.32 分钟前
Java位运算详解:原理、用法及实战场景(面试重点)
开发语言·数据库·python
游乐码37 分钟前
c#万物之父装箱拆箱
开发语言·c#
Scott.W38 分钟前
跟我学Easyi3C Tower Adapter Console(9)
人工智能·python·嵌入式硬件·i3c
多恩Stone1 小时前
【3D-AICG 系列-14】Trellis 2 的 Texturing Pipeline 保留单层薄壳,而 Textured GLB 会变成双层
人工智能·python·算法·3d·aigc
CDwenhuohuo1 小时前
var面试题
开发语言·javascript·ecmascript