Python 通过添加整数合并2个或多个列表
我正在为购物车(某种程度上)编写代码。我遇到了一个问题,当用户购买两次商品时,它应该自动添加其数量和价格 我的文件包含的内容:Python 通过添加整数合并2个或多个列表,python,Python,我正在为购物车(某种程度上)编写代码。我遇到了一个问题,当用户购买两次商品时,它应该自动添加其数量和价格 我的文件包含的内容: 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)
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]数量
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