《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
相关推荐
Y409001几秒前
C语言转Java语言,相同与相异之处
java·c语言·开发语言·笔记
都叫我大帅哥1 小时前
Python的Optional:让你的代码优雅处理“空值”危机
python
曾几何时`3 小时前
基于python和neo4j构建知识图谱医药问答系统
python·知识图谱·neo4j
古月-一个C++方向的小白5 小时前
C++11之lambda表达式与包装器
开发语言·c++
写写闲篇儿6 小时前
Python+MongoDB高效开发组合
linux·python·mongodb
沐知全栈开发6 小时前
Eclipse 生成 jar 包
开发语言
杭州杭州杭州7 小时前
Python笔记
开发语言·笔记·python
tanyongxi667 小时前
C++ AVL树实现详解:平衡二叉搜索树的原理与代码实现
开发语言·c++
阿葱(聪)8 小时前
java 在k8s中的部署流程
java·开发语言·docker·kubernetes
路人蛃8 小时前
通过国内扣子(Coze)搭建智能体并接入discord机器人
人工智能·python·ubuntu·ai·aigc·个人开发