《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 分钟前
【Python 全栈测开之路】Python 进阶:库的使用与第三方生态(标准库+Pip+实战)
java·开发语言·c++·python·ai·c#·pip
子夜江寒2 小时前
基于 OpenCV 的图像形态学与边缘检测
python·opencv·计算机视觉
SmartRadio8 小时前
CH585M+MK8000、DW1000 (UWB)+W25Q16的低功耗室内定位设计
c语言·开发语言·uwb
rfidunion8 小时前
QT5.7.0编译移植
开发语言·qt
少林码僧8 小时前
2.31 机器学习神器项目实战:如何在真实项目中应用XGBoost等算法
人工智能·python·算法·机器学习·ai·数据挖掘
rit84324998 小时前
MATLAB对组合巴克码抗干扰仿真的实现方案
开发语言·matlab
智航GIS9 小时前
10.4 Selenium:Web 自动化测试框架
前端·python·selenium·测试工具
jarreyer9 小时前
摄像头相关记录
python
宝贝儿好9 小时前
【强化学习】第六章:无模型控制:在轨MC控制、在轨时序差分学习(Sarsa)、离轨学习(Q-learning)
人工智能·python·深度学习·学习·机器学习·机器人
大、男人9 小时前
python之asynccontextmanager学习
开发语言·python·学习