← 中文资源

简体中文版本

Counter 计票与排名

用 collections.Counter 做计数、most_common 排名、加减合并与负数过滤:一轮遍历完成选票统计全套操作。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

counts: {'rust': 3, 'go': 3, 'python': 1, 'typescript': 1}
top2: [('rust', 3), ('go', 3)]
combined winner: rust
swing gains: {'rust': 1, 'python': 2}
viable: {'rust': 5, 'python': 1}

实现说明

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()