Python 字典和列表比较

标签 python data-structures

我试图将列表“lines”中的每个项目与字典“dic”进行比较,然后将lines中的项目添加到dic(如果不存在),或者将1添加到中的键值字典。

import string

def uniques():
    file = open("test.txt", "r")
    dic = {}
    data = file.read().replace('\n', ' ')
    strip = removePunctuation(data)
    lines = strip.split(' ')
    print(strip)
    print(lines)

    for item in lines:

        #this produces an error of unhashable type: 'list'
        if lines in dic:
            dic[item] = dic[item] + 1
        else:
            print("else ran")
            dic[item] = 1

    for item in dic:
        print(item, dic[item])
        print("There are " + str(len(dic)) + " items in the dictionary")

def removePunctuation(text):
    text = text.strip()
    return text.rstrip(string.punctuation)

uniques()

最佳答案

if item in dic:
      dic[item] = dic[item] + 1

而不是

if lines in dic:
      dic[item] = dic[item] + 1

关于Python 字典和列表比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52960121/

相关文章:

python - Conda 和 Anaconda 运行不同的 Python 安装?

python - 从文本中删除一行

python - 如何将四维 python numpy 数组乘以第二维索引的向量

python - 遍历列表,比较前面的元素和后面的元素

c++ - 使用C++标准库以对数时间进行堆化

python - Python 字典和数据结构有什么区别?

java - 使用 SQL 创建和构建复杂的座位结构?

Python 自省(introspection) : how to detect what fields are accessed from a method

arrays - 为什么我们应该使用堆栈,因为数组或链表可以完成堆栈可以执行的所有操作

c# - 具有规范布局的搜索树