我添加了一个例子,希望能让这一点更清楚。我试着做到以下几点:把单词dict中没有的句子中的单词添加到一个列表中,然后将这些单词添加到字典中“new_words_dict”。只添加一次单词,不重复,并增加一个计数器来跟踪单词出现的次数。例如,“happy”会在字典中出现一次,计数器为2。在
我可以创建列表并将单词添加到字典中,但是我不能正确地递增字典中的值。在
words = {'abandon':-2,'abandoned':-2,'abandons':-2,'abducted':-2,'abduction':-2,
'abductions':-2,'abhor': -3}
sentence = {'abandon', 'abandoned', 'abhorrent', 'hello', 'smart', 'hello', 'die',
'happy', 'sad', 'up', 'down', 'happy', 'smart','cool', 'clean', 'mean'}
new_words_list = [] #Empty list
new_words_dict = {} #Empty dict
for word in sentence:
if word not in words:
new_words_list.append(word)
print new_words_list
for word in new_words_list:
if word not in new_words_dict:
new_words_dict[word] = {}
new_words_dict[word] =1
else:
if word in new_words_dict:
new_words_dict[word] +=1
print new_words_dict
这将打印新的单词,但值计数器的增量不正确。在
你在用一种令人困惑和不必要的复杂方式来做这件事。collections.Counter可以为您完成大部分工作:
可能这并不是您真正想要的,因为您的代码太坏了。据我所知,它确实做到了你的问题所要求的。在
我同意msw,你的代码是不必要的复杂。不过,既然您想坚持下去并从中学习一些东西,下面是您的代码和一些注释和更正:
请注意,第二个循环中的
new_words_dict[word] = {}
没有任何意义,因为您需要的是计数器而不是字典。在我看不出柜台有什么问题。这可能是因为我更正了您的
else
/elif
语句的缩进(如果您不在这里缩进或者在原始代码中缩进,我就不是sue了?)。在相关问题 更多 >
编程相关推荐