《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
相关推荐
NMBG223 分钟前
[JAVASE] 注解
java·开发语言·spring boot·spring·面试·java-ee·intellij-idea
爱吃馒头爱吃鱼11 分钟前
QML编程中的性能优化
开发语言·qt·性能优化
噔噔噔噔@13 分钟前
JavaScript性能优化的几个方面入手
开发语言·javascript·性能优化
L_cl1 小时前
【NLP 36、CRF条件随机场 —— 源码解读】
人工智能·python·自然语言处理
gallonyin1 小时前
从WorkTool看RPA技术演进——移动端自动化的未来趋势
运维·自动化·rpa
NEET_LH1 小时前
Python个人学习笔记(14):函数(匿名函数、内置函数(下)、三元表达式)
笔记·python·学习
xinxiyinhe1 小时前
Python从基础开发到前沿技术完整生态(应用&技术栈)(2025版)
python·django·flask
RichardK.1 小时前
【C++ STL】 容器详解:pair 学习
开发语言·数据结构·c++·学习
why1512 小时前
go个人论坛项目
开发语言·后端·golang
趋势大仙2 小时前
harmony Next 基础知识点1
开发语言·华为·harmonyos