Python STV投票程序:如何将文本文件投票评分存入二维数组
Solution for STV Vote Scoring Storage and Output
Got it, let's walk through how to implement this in Python step by step. We'll read the vote data, organize it into a 2D structure, and output the results in the format you need.
Sample Vote File Structure
First, let's assume your text file (votes.txt) looks like this (aligns with your problem description):
1 2 3 0 0 2 1 0 3 0 3 0 1 2 0 0 3 2 1 0
Each line is a single ballot, with numbers corresponding to candidates A, B, C, D, E in order.
Python Implementation
Here's the code to handle reading the file, storing the data, and generating the required output:
# List of candidate names in the order they appear in each ballot candidates = ['A', 'B', 'C', 'D', 'E'] ballots = [] # Read and parse the vote file with open('votes.txt', 'r') as file: for line in file: # Skip empty lines (in case the file has them) if not line.strip(): continue # Convert each line into a list of integers (our 2D array row) vote = list(map(int, line.strip().split())) ballots.append(vote) # Transpose the 2D array to get each candidate's scores across all ballots # zip(*ballots) gives tuples of scores for each candidate candidate_scores = list(zip(*ballots)) # Print each candidate's scores in the requested format for name, scores in zip(candidates, candidate_scores): print(f"{name} {scores}")
Breakdown of the Code
- Reading the File: We use a
withstatement to safely open and read the file. Each line is split into integers and added to theballotslist—this is our 2D array where each row represents a single ballot. - Transposing Data:
zip(*ballots)swaps rows and columns. Instead of each element being a full ballot, each element becomes a candidate's scores across all 4 ballots (as a tuple, which fits your output format perfectly). - Output: We pair each candidate name with their scores and print them in the exact format you specified.
Expected Output
Running the code will produce:
A (1, 2, 3, 0) B (2, 1, 0, 3) C (3, 0, 1, 2) D (0, 3, 2, 1) E (0, 0, 0, 0)
Quick Notes
- If your vote file has inconsistent spacing or blank lines, the code skips empty lines to avoid errors.
- If you need scores stored as lists instead of tuples, just convert them with
list(scores)when printing or storing.
内容的提问来源于stack exchange,提问作者Mejdeinstein
相关产品推荐
相关产品推荐

