我有一个看起来很可笑的列表,像这样。
[['Biking', '10'], ['Biking|Gym', '14'], ['Biking|Gym|Hiking', '9'], ['Biking|Gym|Hiking|Running', '27']]
我想把它变成 ['Type', total, %] 的格式,像这样:
[['Biking',60,'34.7%'],['Gym',50,'28.9%'],['Hiking',36,'20.8%'],['Running',27,'15.6%']]
我确定我正在以最困难的方式进行此操作-有人可以为我指出更好的方向吗?我以前使用过 itertools.groupby ,这似乎是一个不错的地方,但我不确定如何在这种情况下实现。
# TODO: This is totally ridiculous.
running = 0
hiking = 0
gym = 0
biking = 0
no_exercise = 0
for r in exercise_types_l:
if 'Running' in r[0]:
running += int(r[1])
if 'Hiking' in r[0]:
hiking += int(r[1])
if 'Gym' in r[0]:
gym += int(r[1])
if 'Biking' in r[0]:
biking += int(r[1])
if 'None' in r[0]:
no_exercise += int(r[1])
total = running + hiking + gym + biking + no_exercise
l = list()
l.append(['Running', running, '{percent:.1%}'.format(percent=running/total)])
l.append(['Hiking', hiking, '{percent:.1%}'.format(percent=hiking/total)])
l.append(['Gym', gym, '{percent:.1%}'.format(percent=gym/total)])
l.append(['Biking', biking, '{percent:.1%}'.format(percent=biking/total)])
l.append(['None', no_exercise, '{percent:.1%}'.format(percent=no_exercise/total)])
l = sorted(l, key=lambda r: r[1], reverse=True)