我有一个嵌套的列表,就像这样[[县政党投票收到]]与数据类型为字符串字符串和int。
我如何获得一个嵌套的列表,并按政党进行汇总?我想要一个表格,比较所有不同的政党和他们的总票数。
我知道我可以只使用字典或熊猫(group_by),但我想学习如何在没有它们的情况下做到这一点。我找不到任何与这一情况直接相关的问题。
###你需要遍历所有的子列表,并将它们的和存储在一个映射:
sums = {}
for i in big_list:
_, party, votes = i # based on the question
sums[party] = sums.get(party, 0) + votes # if it already has a summation
# just get it, otherwise start
# from a summation of zero
# to get them, just iterate over the map
for party, total_votes in sums.items():
print(party, total_votes)
###字典将会更有效率,但还有其他(较慢的)方法。
例如:排序
totalList = []
for _,party,votes in sorted(voteList,key=lambda v:v[1]):
if not totalList or totalList[-1][0] != party:
totalList.append([party,votes])
else:
totalList[-1][1] += votes
使用不同政党名称的多个传递:
parties = {party for _,party,_ in voteList} # set of distinct parties
totalList = [ [party,sum(votes for _,p,votes in voteList if p==party)]
for party in parties ]
还有一个来自集合的Counter类,它是这种类型的一个专门的字典:
from collections import Counter
totals = Counter()
for _,party,votes in voteList: totals[party] += votes