重申列表和词典

时间:2012-11-25 06:59:34

标签: python dictionary python-3.x

在下面的代码中,为什么我的代码没有正确迭代?我可能错过了一行,但我无法弄清楚为什么它不起作用。

我有一个带有以下测试用例的函数:

>>> 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

2 个答案:

答案 0 :(得分:2)

我这样做的方式是这样的:

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)

答案 1 :(得分:1)

如果你有2.7:

import operator
from collections import Counter
listoflists = [['A', 'B', 'C', 'D'], ['B', 'A', 'C', 'D'], ['B', 'C', 'D', 'A']]

def borda(listoflists):
    outdict = sum([Counter({item[x]:3-x}) for item in listoflists for x in range(3]],
                  Counter())
    highestitem = max(outdict.iteritems(), key=operator.itemgetter(1))[0]
    outlist = [outdict[item[0]] for item in sorted(outdict.iteritems(),
                                                   key=operator.itemgetter(0))]
return (highestitem, outlist)

看看ma ..没有循环: - )

查看http://ua.pycon.org/static/talks/kachayev/index.html以了解为何更好。