我正在为一个购物车(某种)编写代码,但是我遇到一个问题,当用户两次购买商品时,应该自动添加其数量和价格。
我的文件包含什么:
Apple 300 2 kg
Shirt Medium Blue 1350 3 shirt
Shirt Medium Blue 1850 4 shirt
我希望将这件衬衫“ Medium Blue”合并。 到目前为止,我正在尝试
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]数量
答案 0 :(得分:-1)
-8px
输出:
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)