按照会员和产品进行累计计算产品的数量
创始人
2024-08-24 05:00:21
0

以下是一个示例代码,演示了如何按照会员和产品进行累计计算产品的数量:

# 创建一个空字典来存储会员和产品的数量
product_count = {}

# 假设有以下产品购买记录
purchases = [
    {"member": "Alice", "product": "Apple", "quantity": 2},
    {"member": "Bob", "product": "Banana", "quantity": 3},
    {"member": "Alice", "product": "Orange", "quantity": 1},
    {"member": "Charlie", "product": "Apple", "quantity": 4},
    {"member": "Bob", "product": "Orange", "quantity": 2},
    {"member": "Charlie", "product": "Banana", "quantity": 1},
]

# 遍历购买记录
for purchase in purchases:
    member = purchase["member"]
    product = purchase["product"]
    quantity = purchase["quantity"]
    
    # 检查会员是否已经存在于字典中
    if member in product_count:
        # 检查产品是否已经存在于会员的字典中
        if product in product_count[member]:
            # 如果产品已经存在,累加数量
            product_count[member][product] += quantity
        else:
            # 如果产品不存在,将产品添加到会员的字典中,并设置数量
            product_count[member][product] = quantity
    else:
        # 如果会员不存在,创建一个新的字典,并将产品添加到字典中,并设置数量
        product_count[member] = {product: quantity}
        
# 打印结果
for member, products in product_count.items():
    print(f"会员: {member}")
    for product, quantity in products.items():
        print(f"产品: {product}, 数量: {quantity}")
    print()

输出结果:

会员: Alice
产品: Apple, 数量: 2
产品: Orange, 数量: 1

会员: Bob
产品: Banana, 数量: 3
产品: Orange, 数量: 2

会员: Charlie
产品: Apple, 数量: 4
产品: Banana, 数量: 1

这个示例代码使用了一个字典来存储会员和产品的数量。首先,遍历购买记录,对于每一条记录,检查会员是否已经存在于字典中。如果存在,再检查产品是否已经存在于会员的字典中。如果存在,累加数量;如果不存在,将产品添加到会员的字典中,并设置数量。如果会员不存在,创建一个新的字典,并将产品添加到字典中,并设置数量。最后,打印结果。

相关内容

热门资讯

推荐十款!德普之星私人局辅助免... 推荐十款!德普之星私人局辅助免费,wepoker公共底牌,教你攻略(有挂教程);人气非常高,ai更新...
科技介绍!we-poker辅助... 此外,数据分析德州(we-poker辅助软件教程)辅助神器app还具备辅助透视行为开挂功能,通过对客...
解密关于!wepoker软件安... 解密关于!wepoker软件安装包,epoker底牌透视,详细教程(有挂透明)关于wepoker软件...
玩家必看科普!哈糖大菠萝怎么挂... 《玩家必看科普!哈糖大菠萝怎么挂,hardrock透视工具,新2025版(有挂技巧)》 哈糖大菠萝怎...
六分钟了解!WePoKer辅助... 六分钟了解!WePoKer辅助器,wepoker透视脚本免费下载pc,教你攻略(有挂透视)准备好在w...
总算明白!wepoker怎么下... 总算明白!wepoker怎么下载游戏,pokemmo手机版透视脚本,爆料教程(有挂神器);《WPK辅...
一分钟了解!竞技联盟透视,we... 一分钟了解!竞技联盟透视,wepoker怎么看牌型,可靠教程(有挂教程);支持多人共享记分板与复盘,...
重要通知!werplan外挂,... 1、重要通知!werplan外挂,wepoker可以免费玩吗,可靠教程(有挂攻略);详细教程。2、w...
分享一款!wepoker怎么挂... 分享一款!wepoker怎么挂飞机,有没有人wepoker,必备教程(有挂技巧);支持多人共享记分板...
技巧知识分享!菠萝辅助器免费版... 技巧知识分享!菠萝辅助器免费版的功能介绍,wepoker有辅助工具吗,详细教程(有挂技巧)是由北京得...