2013-08-20 77 views
-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”。什么是错误?

+2

你有'从集合进口defaultdict'吗? –

+0

你是否从集合导入defaultdict'? – roippi

+0

你是如何运行它的?你可以在交互模式下运行python吗? – flornquake

回答

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 
0

假设蟒蛇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 

将创建defaultdict,具有计数和键填充它,然后做你的打印(我假设只是调试/完整性检查的东西......)

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语句即可。