刚开始学习,都不懂,有没有人可以给我看看,这看着不难,但就是不知道怎么写。
可以使用Python中的字典来实现将投票结果进行汇总统计,代码如下:
votes = [['张三',6],['李四',8],['王二',3],['张三',5],['王二',4],['张三',3]]
result = {}
for candidate, count in votes:
if candidate not in result:
result[candidate] = count
else:
result[candidate] += count
print(result)
输出结果为 {'张三': 14, '李四': 8, '王二': 7}
。
3:
votes = [['张三',6],['李四',8],['王二',3],['张三',5],['王二',4],['张三',3]]
result = {}
for vote in votes:
name, score = vote
if name in result:
result[name] += score
else:
result[name] = score
print(result)
4:
votes = [['张三',6],['李四',8],['王二',3],['张三',5],['王二',4],['张三',3]]
vote_dict = {}
for vote in votes:
if vote[0] not in vote_dict:
vote_dict[vote[0]] = [vote[1], 1]
else:
vote_dict[vote[0]][0] += vote[1]
vote_dict[vote[0]][1] += 1
result = {}
for name, vote_info in vote_dict.items():
result[name] = round(vote_info[0] / vote_info[1], 2)
print(result)
votes = [ ['张三',6],['李四',8],['王二',3],['张三',5] ,['王二',4],['张三',3]]
## 第3问
result = {}
for item in votes:
if item[0] not in result.keys():
result[ item[0] ] = item[1]
else:
result[ item[0] ] = result.get(item[0]) + item[1]
print(result)
## 第4问
counts = {}
result2 = {}
for item in votes:
if item[0] not in counts.keys():
counts[ item[0] ] = 1
else:
counts[ item[0] ] = counts.get(item[0]) + 1
for k,v in result.items():
result2[k] = round( v/counts.get(k),2 )
print(result2)