按照会员和产品进行累计计算产品的数量
创始人
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

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

相关内容

热门资讯

透视私人局!aa poker辅... 透视私人局!aa poker辅助(透视)辅助插件工具(好像真的有挂);1、构建自己的aa poker...
透视肯定!aapoker辅助器... 透视肯定!aapoker辅助器是真的吗(透视)透视插件(一直是有挂)1)aapoker辅助器是真的吗...
透视美元局!aapoker辅助... 透视美元局!aapoker辅助插件工具(透视)透视脚本下载(确实是有挂)1、每一步都需要思考,不同水...
透视美元局!aapoker插件... 透视美元局!aapoker插件(透视)免费透视脚本(一直存在有挂)1、首先打开aapoker插件最新...
透视能赢!aapoker透视方... 透视能赢!aapoker透视方法(透视)辅助插件工具(一直存在有挂);1、超多福利:超高返利,海量正...
透视工具!aapoker辅助工... 透视工具!aapoker辅助工具安全吗(透视)万能辅助器(本来真的有挂);1、首先打开aapoker...
透视新版!aapoker免费透... 透视新版!aapoker免费透视脚本(透视)万能辅助器(一贯是有挂);1、超多福利:超高返利,海量正...
透视辅助!aapoker如何设... 透视辅助!aapoker如何设置胜率(透视)真的假的(真是存在有挂)1)aapoker如何设置胜率辅...
透视了解!aapoker透视脚... 透视了解!aapoker透视脚本入口(透视)透视方法(一直有挂);1、在aapoker透视脚本入口a...
透视辅助!aapoker插件(... 透视辅助!aapoker插件(透视)发牌逻辑(一直真的是有挂)在进入aapoker插件辅助挂后,参与...