输入:
Choc 5
Vani 10
Stra 7
Choc 3
Stra 4
END
def process_input(lst):
result = []
for string in lines:
A=string.split()
result.append([A[0],int(A[1])])
return result
def merge_products(invent):
# your code here
# DON’T modify the code below
str = input()
lines = []
while str != 'END':
lines.append(str)
str = input()
inventory1 = process_input(lines)
merge_products(inventory1)
print(inventory1)
来自此输出
[['Choc', 5], ['Vani', 10], ['Stra', 7], ['Choc', 3], ['Stra', 4]]
我需要获得此输出
[['Choc', 8], ['Vani', 10], ['Stra', 11]]
如何将整数组合在同一个字符串下?
答案 0 :(得分:3)
与Kaushik NP的答案类似,但使用collections.Counter
from collections import Counter
def merge_products(inventory):
groceries = Counter()
for item, count in inventory:
groceries[item] +=count
return [[item, count] for item, count in groceries.items()]
这在功能上是等效的,但Counter
会为您处理默认值。对于大型商品列表来说,它也可能更具性能,但在您运营的规模上,这可能不是什么大问题。
答案 1 :(得分:0)
使用defaultdict
存储值并添加值。
from collections import defaultdict
def merge_products(invent):
d = defaultdict(int)
for x,y in invent:
d[x]+=y
return [[k,v] for k,v in d.items()]
#driver values:
>>> merge_products([['Choc', 5], ['Vani', 10], ['Stra', 7], ['Choc', 3], ['Stra', 4]])
=> [['Choc', 8], ['Vani', 10], ['Stra', 11]]
如果您想要保留您找到它们的订单,请改用OrderedDict
。
def merge_products(invent):
d = OrderedDict()
for x,y in invent:
if d.get(x,None)==None :
d[x]=y
else :
d[x]+=y
return [[k,v] for k,v in d.items()]
答案 2 :(得分:0)
你可以使用字典:
def merge_products(invent):
# your code here
result = {}
for item in invent:
if item[0] not in result:
result[item[0]] = item[1]
else:
result[item[0]] += item[1]
return result
请注意,您将使用返回的值,而不是作为参数传递的值:
print(merge_products(inventory1))