<p>您可以在这里使用<code>collections.defaultdict</code>。dict在这里是更好的数据结构,因为您可以访问与<code>O(1)</code>类型中的任何<code>'Type'</code>相关的值。你知道吗</p>
<pre><code>>>> from collections import defaultdict
>>> lis = [['Biking', '10'], ['Biking|Gym', '14'], ['Biking|Gym|Hiking', '9'], ['Biking|Gym|Hiking|Running', '27']]
>>> total = 0
>>> dic = defaultdict(lambda :[0])
for keys, val in lis:
keys = keys.split('|')
val = int(val)
total += val*len(keys)
for k in keys:
dic[k][0] += val
...
for k,v in dic.items():
dic[k].append(format(v[0]/float(total), '.2%'))
...
>>> dic
defaultdict(<function <lambda> at 0xb60e772c>,
{'Gym': [50, '28.90%'],
'Biking': [60, '34.68%'],
'Running': [27, '15.61%'],
'Hiking': [36, '20.81%']})
</code></pre>
<p>访问值:</p>
<pre><code>>>> dic['Biking']
[60, '34.68%']
>>> dic['Hiking']
[36, '20.81%']
</code></pre>
<p><strong>另一种选择是使用dict作为值而不是列表:</strong></p>
<pre><code>>>> dic = defaultdict(lambda :dict(val = 0))
>>> total = 0
for keys, val in lis:
keys = keys.split('|')
total += int(val)*len(keys)
for k in keys:
dic[k]['val'] += int(val)
...
for k,v in dic.items():
dic[k]['percentage'] = format(v['val']/float(total), '.2%')
...
>>> dic
defaultdict(<function <lambda> at 0xb60e7b8c>,
{'Gym': {'percentage': '28.90%', 'val': 50},
'Biking': {'percentage': '34.68%', 'val': 60},
'Running': {'percentage': '15.61%', 'val': 27},
'Hiking': {'percentage': '20.81%', 'val': 36}})
</code></pre>
<p>访问值:</p>
<pre><code>#Return percentage related to 'Gym'
>>> dic['Gym']['percentage']
'28.90%'
#return the total sum of 'Biking'
>>> dic['Biking']['val']
60
</code></pre>