[英](Python 3) How do I combine products of a list?
輸入:
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]]
如何在相同的字符串下組合整數?
類似於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
會為您處理默認值。 對於大型項目列表而言,它也可能更具性能,但在您運營的規模上可能並不是什么大不了的事。
使用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值:
>>> 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()]
你可以使用字典:
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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.