f = open("name.txt", encoding="utf-8")
names = f.readlines()
f.close()
f = open("vote.txt", encoding="utf-8")
votes = f.readlines()
f.close()
D = {}
NUM = 0
for vote in votes:
num = len(vote.split())
if num == 1 and vote in names:
D[vote[:-1]] = D.get(vote[:-1], 0)+1 #################
NUM += 1
l = list(D.items()) ##########################
l.sort(key=lambda s: s[1], reverse=True) #################
name = l[0][0]
score = l[0][1]
print("有效票数为:{} 当选村民为:{},票数为:{}".format(NUM, name, score))
哪位可以给我解释一下上边有#的这几句是什么意思
第二个是转化为列表,第三个是按照票数排序
三处分别涉及三个知识点
1、python字典的get方法,和直接用方括号差不多但是可以设置空值的默认值(这里是计数所以默认值是0)
https://www.runoob.com/python3/python3-att-dictionary-get.html
2、python字典的item方法,返回一个可遍历的key/value 对,list强转以后就是一个元组构成的list,每个元组两个元素分别是key和对应value
https://www.runoob.com/python3/python3-att-dictionary-items.html
3、第三个有两个知识点一个是list的排序,key是指定的排序方法,还有一个是lamda的匿名函数,这块我觉得菜鸟教程的例子写的不好就不放连接了。你自己百度一下相关的东西把