python投票系统代码
时间: 2024-10-31 21:05:29 浏览: 34
在Python中实现一个简单的投票系统,通常会涉及数据结构如字典、列表或者集合来存储选票和候选人。下面是一个简化的例子,展示如何创建一个命令行投票程序:
```python
class Election:
def __init__(self):
self.votes = {}
def add_candidate(self, candidate):
if candidate not in self.votes:
self.votes[candidate] = 0
def vote(self, voter, candidate):
if voter and candidate:
self.votes[candidate] += 1
def get_leader(self):
return max(self.votes, key=self.votes.get)
# 使用示例
election = Election()
election.add_candidate("A")
election.add_candidate("B")
election.add_candidate("C")
voter1 = "Alice"
voter2 = "Bob"
election.vote(voter1, "A")
election.vote(voter2, "B")
print(f"当前领先者: {election.get_leader()} ({election.votes[election.get_leader()]})")
阅读全文