脚本不打印字数

时间:2013-08-20 16:02:21

标签: python

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

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”。错误是什么?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

将创建defaultdict,用计数和键填充它并进行打印(我假设它只是调试/健全检查的东西......)

答案 2 :(得分: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语句。