Verwenden Sie eine Liste, wie der Schlüssel in ein Python dict

Ich habe zwei Listen, und ich brauche, um den Rang Ihrer Elemente mit der Borda-positions-ranking. also ich habe diese Funktion, aber ich habe diesen Fehler:

TypeError: unhashable type: 'list'. 

Wie von anderen Antworten, Das problem ist, dass ich nicht verwenden können, eine Liste als key in einem dict, da dict-Schlüssel müssen unveränderlich sein.So habe ich ein Tupel statt, aber der Fehler bleibt.

The files of the two lists look like this
list1 = [([('diritti', 'S'), ('umani', 'A')]), ([('violazioni', 'S'), ('dei', 'E'), ('diritti', 'S'), ('umani', 'A')]), ([('forze', 'S'), ('di', 'E'), ('sicurezza', 'S')]), ([('violazioni', 'S'), ('dei', 'E'), ('diritti', 'S')]), ([('Nazioni', 'SP'), ('Unite', 'SP')]), ([('anni', 'S'), ('di', 'E'), ('carcere', 'S')])] 
list2 = [([('anni', 'S'), ('di', 'E'), ('carcere', 'S')]), ([('diritti', 'S'), ('umani', 'A')]), ([('forze', 'S'), ('di', 'E'), ('sicurezza', 'S')]), ([('violazioni', 'S'), ('dei', 'E'), ('diritti', 'S'), ('umani', 'A')]), ([('violazioni', 'S'), ('dei', 'E'), ('diritti', 'S')]), ([('Nazioni', 'SP'), ('Unite', 'SP')]), ([('uso', 'S'), ('eccessivo', 'A'), ('della', 'E'), ('forza', 'S')])] 

Ich öffnen Sie die zwei Dateien als Liste auf diese Weise

list1 = codecs.open('/home/list1', 'r', 'utf-8').read()
list2 = codecs.open('/home/list2', 'r', 'utf-8').read()
li = ast.literal_eval(list1)
lii = ast.literal_eval(list2)

def borda_sort(lists):
###Borda’s positional ranking combines ranked lists using information of the ordinal ranks of the elements in each list.Given lists t1, t2, t3 ... tk, for each candidate c and list ti, the score B ti (c) is the number of candidates ranked below c in ti. So The total Borda score is B(c) = ∑ B ti (c) The candidates are then sorted by descending Borda scores. Given the lists = [ ['a', 'c'], ['b', 'd', 'a'], ['b', 'a', 'c', 'd'] ], the output will be ['b', 'a', 'c', 'd']
    scores = {}
    for l in lists:
        for idx, elem in enumerate(reversed(l)):
            if not elem in scores:
                scores[elem] = 0
            scores[elem] += idx
    return sorted(scores.keys(), key=lambda elem: scores[elem], reverse=True)

lists = zip(li, lii)
print borda_sort(lists)

Kann jemand helfen?

  • Listen können nicht als Schlüssel verwendet werden, die für dict. Vielleicht sind casting-Listen zu strings lösen Ihr Problem?
  • Duplikat von this.
  • Vielleicht spiegeln Sie Ihre Liste mit einem dict?
  • Sie sagen, dass Sie ein Tupel, aber ich sehe nicht überall. Können Sie uns sagen, welche Zeile der Fehler kommt?
  • Könnten Sie einige Beispiel für die Eingabe in list1 und list2 und die erwarteten Ergebnisse?
  • unrelated: könnten Sie json zum speichern der Listen anstelle von Python-Literale (ast.literal_eval()).

InformationsquelleAutor sss | 2015-05-16
Schreibe einen Kommentar