投票系统脚本出现IndexError问题求助及代码优化建议
First, let's break down the error you're seeing:IndexError: list index out of range happens because your code hardcodes references to indexes 0 through 3 (assuming exactly 4 candidates), but your votes list likely has fewer than 4 elements. For example, if there are only 2 candidates, votes[3] doesn't exist—lists in Python are zero-indexed, so the last valid index is always len(votes) - 1.
A More Robust & Concise Implementation
Instead of writing repetitive conditionals tied to 4 candidates (which breaks easily if you add/remove candidates), let's rewrite the function to handle any number of candidates dynamically:
def get_winner(votes, cands): if not votes or not cands: print("No votes or candidates provided.") return max_vote_count = max(votes) # Collect all candidates who received the maximum votes winning_candidates = [ candidate for idx, candidate in enumerate(cands) if votes[idx] == max_vote_count ] if len(winning_candidates) > 1: print(f"We have a tie between: {', '.join(winning_candidates)}") else: print(f"Congratulations candidate {winning_candidates[0]}! You win")
Key Improvements:
- Flexible Candidate Support: Works for any number of candidates (1, 4, 10, etc.) instead of being locked to 4.
- Eliminates Redundancy: No more repetitive if statements for each candidate or redundant tie checks (your original code had 4 identical tie conditions).
- Error Prevention: Added a check for empty
votesorcandslists to avoid unexpected crashes. - Readability: Uses list comprehension to cleanly collect winners, making the logic straightforward to follow.
Example Usage:
# Test with 4 candidates (your original scenario) votes = [15, 22, 18, 22] cands = ["Alice", "Bob", "Charlie", "Diana"] get_winner(votes, cands) # Output: "We have a tie between: Bob, Diana" # Test with 2 candidates votes = [30, 25] cands = ["Eve", "Frank"] get_winner(votes, cands) # Output: "Congratulations candidate Eve! You win"
This approach is far more maintainable and avoids the index error entirely because it never assumes a fixed number of candidates.
内容的提问来源于stack exchange,提问作者C Plant

