实现说明
Counter 计票与排名以函数 main为骨架。
使用要点
- 演示输出是带标签的(
counts:、top2:、combined winner:),每个操作都会留下自己的一行标注。
常见问题
运行「Counter 计票与排名」会打印什么?
整个文件跑完,输出行以 counts:、top2:、combined winner: 这类前缀开头。
主要签名是 def main() -> None
代码示例
from collections import Counter
VOTES = ['rust', 'go', 'rust', 'python', 'go', 'rust', 'typescript', 'go']
def main() -> None:
tally = Counter(VOTES)
print('counts:', dict(tally))
# most_common:按票数降序取前二
print('top2:', tally.most_common(2))
# 两轮投票合并:Counter 相加;差值找流失票
round_two = Counter({'rust': 4, 'go': 2, 'python': 3})
combined = tally + round_two
swing = round_two - tally
print('combined winner:', combined.most_common(1)[0][0])
print('swing gains:', dict(+swing))
# 过滤低票项:保持 Counter 类型
viable = +Counter({'rust': 5, 'go': 0, 'python': 1})
print('viable:', dict(viable))
if __name__ == '__main__':
main()