Counter Tallying And Ranking

Tally hashable items with collections.Counter — most_common ranking, arithmetic merging, and negative-count filtering in one pass.

PythonData Integrity

Code

pythonsnippet
26 lines
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()

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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}

How the snippet works

Counter Tallying And Ranking comes down to the function main.

Using it

The primary signature is def main() -> None

Running the file prints labeled results such as counts:, top2:, combined winner: — each operation’s effect is visible in the output.

Interactive Tools for This Topic

FAQ

What does Counter Tallying And Ranking print when run?
No setup needed: run the file and look for labeled lines like `counts:`, `top2:`, `combined winner:` in the output.