擅长:python、mysql、java
<p>使用集合.default\u dict建立一个字典来计算你的项目。你知道吗</p>
<pre><code>In [1]: from collections import defaultdict
In [2]: items = defaultdict(int)
In [3]: Foodlist = ['apple, carrot, banana','chocolate, apple', 'strawberry, or
...: ange, carrot']
In [4]: Quantity = ['1,2,1','2,5','1,2']
In [5]: for which, counts in zip(Foodlist, Quantity):
...: foods = [w.strip() for w in which.split(',')] # Split the foods and remove trailing spaces
...: nums = [int(c) for c in counts.split(',')] # Split the counts are convert to ints
...: for f, n in zip(foods, nums):
...: items[f] += n
...:
In [6]: items
Out[6]:
defaultdict(int,
{'apple': 6,
'banana': 1,
'carrot': 2,
'chocolate': 2,
'orange': 2,
'strawberry': 1})
In [7]:
</code></pre>