请求为STV投票系统Python程序添加候选人首选项票数统计功能
Hey there! Let's get this STV first-preference vote tallying sorted out for you. Based on the data and existing code you shared, here's a straightforward way to add the functionality you need:
First, let's clarify the data structure we're working with: your 2D array has one row per ballot, and each column corresponds to a candidate's preference rank (1 = first choice, 2 = second, 3 = third, 0 = not selected). To count first-preference votes, we just need to track how many times each candidate gets a rank of 1 across all ballots.
Step-by-Step Implementation with Code
Assuming your existing ballot data is stored in the votes variable (like the output you showed), here's how to build the tally:
# Your existing ballot data from the program output votes = [['1', ' 2', ' 3', ' 0', ' 0'], ['2', ' 3', ' 1', ' 0', ' 0'], ['3', ' 1', ' 0', ' 0', ' 2'], ['0', ' 2', ' 0', ' 3', ' 1']] # Initialize a counter for each candidate (1-5) starting at 0 first_preference_counts = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} # Loop through each ballot to count first preferences for ballot in votes: # Clean up the ballot data: remove extra spaces and convert to integers cleaned_ballot = [int(item.strip()) for item in ballot] # Find which candidate got the first preference (rank = 1) for candidate_index, rank in enumerate(cleaned_ballot): if rank == 1: # Candidate number is index + 1 (since lists are 0-indexed) candidate_num = candidate_index + 1 first_preference_counts[candidate_num] += 1 break # Each ballot only has one first choice, so we can stop here # Print the final tally print("=== First-Preference Vote Results ===") for candidate, count in sorted(first_preference_counts.items()): print(f"Candidate {candidate}: {count} vote(s)")
What This Code Does
- Data Cleaning: The original array has elements with extra spaces (like
' 2'), so we usestrip()to remove those and convert everything to integers for easy comparison. - Counter Setup: We use a dictionary to track votes per candidate—this makes it easy to map candidate numbers to their vote counts.
- Tally Logic: For each ballot, we look for the rank of 1, find the corresponding candidate (index + 1), and increment their count. We break out of the inner loop once we find the first preference to save a bit of processing time.
Expected Output
When you run this code, you'll see:
=== First-Preference Vote Results === Candidate 1: 1 vote(s) Candidate 2: 1 vote(s) Candidate 3: 1 vote(s) Candidate 4: 0 vote(s) Candidate 5: 1 vote(s)
This matches your ballot data perfectly: each of the 4 valid first preferences goes to candidates 1, 3, 2, and 5 respectively, with candidate 4 getting no first-choice votes.
内容的提问来源于stack exchange,提问作者Kareem

