首页 > 解决方案 > 合并 2 个或更多列表并添加整数

问题描述

我正在为购物车编写代码(有点)我遇到了一个问题,当用户购买两次商品时,它应该自动添加其数量和价格。

我的文件包含的内容:

Apple 300 2 kg
Shirt Medium Blue 1350 3 shirt
Shirt Medium Blue 1850 4 shirt

我希望这件中蓝色衬衫合并。到目前为止我正在尝试什么

l = -1
lol = []


for line in lines:
    l += 1
    shirt = (line.rsplit(" ", 3))
    lol.append(shirt)
    if shirts[l][0] in shirt:
        print('found')

我怎样才能让程序检查行并添加它的索引 [1] 是价格和 [2] 数量

标签: python

解决方案


s = """Apple 300 2 kg
Shirt Medium Blue 1350 3 shirt
Shirt Medium Blue 1850 4 shirt"""

from collections import Counter
import re

m = re.findall('([^\d]+)(\d+)\s+(\d+)\s+(.*)', s)
c_price = Counter()
c_items = Counter()
for g in m:
    c_price.update( {(g[0].strip(), g[3]): int(g[1])}  )
    c_items.update( {(g[0].strip(), g[3]): int(g[2])}  )

for (item_name, item_type), count in c_items.items():
    print(item_name, c_price[(item_name, item_type)], count, item_type)

输出:

Apple 300 2 kg
Shirt Medium Blue 3200 7 shirt

推荐阅读