在下面的代码中,为什么我的代码不能正确迭代?我可能漏掉了一行,但我不明白为什么它不起作用。
我有一个带有以下测试用例的函数:
>>> borda([['A', 'B', 'C', 'D'], ['B', 'A', 'C', 'D'], ['B', 'C', 'D', 'A']])
('B', [5, 8, 4, 1])
其中参数中的列表是排名,每个#1排名获得3分,#2获得2分,#3获得1分,其他排名没有任何得分。不一定有四种选择。元组中的第一个元素应该是得分最高的选项,第二个元素是每个选项获得的得分,按字母顺序排列。
我还没有完成该函数,但我试图获取一个选择字典作为按字母顺序排列的键,并将排名计数作为值,但输出只是最后一个的字典参数中最后一个列表的元素。
L = ['A', 'B', 'C', 'D'] #This is referenced outside the function since it might change
D = {}
i = 0
num = 0
while num < len(L):
num += 1
for choice in L:
while i < len(parameter):
for item in parameter:
if item[0] == choice:
D[choice] = D.get(choice, 0) + 3
if item[1] == choice:
D[choice] = D.get(choice, 0) + 2
if item[2] == choice:
D[choice] = D.get(choice, 0) + 1
i += 1
return D
最佳答案
我这样做的方式是这样的:
import operator
from collections import defaultdict
listoflists = [['A', 'B', 'C', 'D'], ['B', 'A', 'C', 'D'], ['B', 'C', 'D', 'A']]
def borda(listoflists):
outdict = defaultdict(int)
for item in listoflists:
outdict[item[0]] += 3
outdict[item[1]] += 2
outdict[item[2]] += 1
highestitem = max(outdict.iteritems(), key=operator.itemgetter(1))[0]
outlist = [outdict[item[0]] for item in sorted(outdict.keys())]
return (highestitem, outlist)
更新:
我不确定为什么您无法import
标准模块,但如果出于某种原因您被禁止使用import
语句,这里有一个版本仅内置函数:
listoflists = [['A', 'B', 'C', 'D'], ['B', 'A', 'C', 'D'], ['B', 'C', 'D', 'A']]
def borda(listoflists):
outdict = {}
for singlelist in listoflists:
# Below, we're just turning singlelist around in order to
# make use of index numbers from enumerate to add to the scores
for index, item in enumerate(singlelist[2::-1]):
if item not in outdict:
outdict[item] = index + 1
else:
outdict[item] += index + 1
highestitem = max(outdict.iteritems(), key=lambda i: i[1])[0]
outlist = [outdict[item[0]] for item in sorted(outdict.keys())]
return (highestitem, outlist)
关于python - 重申列表和字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13548996/