Python:使用列表作为字典键

问题描述 投票:1回答:1

我确定解决我的问题的方法很简单,但我找不到它。

运行时,我得到

TypeError:不可散列的类型:'列表'

由于我正在使用列表,因此可以预期:

import operator
import shutil

def start(source):
    source=open('Book.txt', 'r', encoding='UTF-8')
    wordslist=[]
    for word in source:
        content=word.lower().split()
        for each_word in content:
            #print(each_word)
            wordslist.append(content)

    #cleanuptext(wordslist)
    sortdictionnary(wordslist)
'''
def cleanuptext(wordslist):
    cleanwords=[]
    for cleanword in wordslist:
        symbols=',.'
        for i in range(0, len(symbols)):
            cleanword = str(cleanword).replace(symbols[i], "")
            if len(cleanword) > 0:
                print(cleanword)
                cleanwords.append(cleanword)
'''
def sortdictionnary(wordslist):
    counter={}
    for word in wordslist:
        if word in counter:
            counter[word] += 1
        else:
            counter[word] = 1
    for key, value in sorted(counter.items(), key=operator.itemgetter(0)):
        print(key, value)
start(source='Book.txt')

如何避免此问题并能够在字典中使用列表?

虽然我尝试使用Counter,但遇到了同样的问题:

import operator
import shutil
from collections import Counter


def start(source):
    source=open('Book.txt', 'r', encoding='UTF-8')
    wordslist=[]
    for word in source:
        content=word.lower().split()
        for each_word in content:
            #print(each_word)
            wordslist.append(content)

    #cleanuptext(wordslist)
    sortdictionnary(wordslist)
'''
def cleanuptext(wordslist):
    cleanwords=[]
    for cleanword in wordslist:
        symbols=',.'
        for i in range(0, len(symbols)):
            cleanword = str(cleanword).replace(symbols[i], "")
            if len(cleanword) > 0:
                print(cleanword)
                cleanwords.append(cleanword)
'''
def sortdictionnary(wordslist):
    coun = Counter()
    for word in wordslist:
        if word in coun:
            coun[word] += 1
        else:
            coun[word] = 1
    for key, value in sorted(coun.items(), key=operator.itemgetter(0)):
        print(key, value)
start(source='Book.txt')

感谢和问候

python list dictionary hash
1个回答
0
投票

一个问题是list是可变的,您不能在字典中使用可变值作为键。另一种方法是使用tuple

content = tuple(word.lower().split())

要了解Python不想使用可变值作为键的原因,请考虑将两个不同的键ab放入具有两个值的字典中,然后对可变a进行突变(第一个键)这样它等于b ...字典应该怎么办?在Python字典中,不能有两个具有不同值的相等键。

Tuples可以作为键,因为它们类似于列表,但不可变。

© www.soinside.com 2019 - 2024. All rights reserved.