-1

我有一个脚本可以在 alist 中找到单词重复:

newm = [u'life', u'selection', u'squire', u'naturalist', u'patriarch', u'home', u'man', u'public', u'nbsp', u'born', u'naturalist', u'theory', u'selectionbecame', u'foundation', u'country', u'gentleman', u'suggesting', u'class', u'time', u'death', u'evolutionary', u'imagery', u'ofscience', u'literature']
print newm

#count for list
counts = defaultdict(int)
print "uyti"
for x in newm:
    counts[x]+=1

print counts

该程序甚至不打印“uyti”。错误是什么?

4

3 回答 3

0

假设 python 2.5+

from collections import defaultdict

newm = [u'life', u'selection', u'squire', u'naturalist', u'patriarch', u'home', u'man', u'public', u'nbsp', u'born', u'naturalist', u'theory', u'selectionbecame', u'foundation', u'country', u'gentleman', u'suggesting', u'class', u'time', u'death', u'evolutionary', u'imagery', u'ofscience', u'literature']
print newm

#count for list
counts = defaultdict(int)
print "uyti"
for x in newm:
   counts[x]+=1

print counts

将创建默认字典,用计数和键填充它并进行打印(我认为这只是调试/健全性检查的东西......)

于 2013-08-20T16:12:59.097 回答
0

如果您只想知道哪些单词是重复的,那么有一种更简单的方法:

words = set(newm)
dups = [(w, newm.count(w)) for w in words if newm.count(w) > 1]
print dups

这会给你[(u'home', 2), (u'naturalist', 2)]。要找出所有单词的计数,只需从列表理解中删除 if 语句。

于 2013-08-20T16:20:55.980 回答
0
from collections import defaultdict
newm = [u'life', u'selection', u'squire', u'naturalist', u'patriarch', u'home', u'man', u'public', u'nbsp', u'born', u'naturalist', u'theory', u'selectionbecame', u'foundation', u'country', u'gentleman', u'suggesting', u'class', u'time', u'death', u'evolutionary', u'imagery', u'ofscience', u'literature',u'home']

#count for list

counts = defaultdict(int)

for x in newm:
   counts[x]+=1

print counts
于 2013-08-20T16:12:11.020 回答