[英]Python Dictionary and List Comparing
I am trying to compare each item in a the list "lines" to the dictionary "dic", and then add the item from lines to dic if it doesn't exist, or add 1 to the value of the key in the dictionary. 我试图将列表“ 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()
its 它的
if item in dic:
dic[item] = dic[item] + 1
instead of 代替
if lines in dic:
dic[item] = dic[item] + 1
if item in dic.values():
instead of if lines in dic:
而不是
if lines in dic:
的if lines in dic:
This would create a dict_value list. 这将创建一个dict_value列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.