簡體   English   中英

Python字典和列表比較

[英]Python Dictionary and List Comparing

我試圖將列表“ lines”中的每個項目與字典“ dic”進行比較,然后將項目從行添加到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
if item in dic.values():

而不是if lines in dic:if lines in dic:

這將創建一個dict_value列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM