Python循环改进

时间:2013-12-03 12:05:20

标签: python loops

我想知道如何有效地根据另一个数组中的单词计算数组上单词的分布。

我们获得了一系列单词test,其任务是汇总新数组tests的单词出现次数

for word in test:
    if word not in s:
        mydict[s.count(word)] = 0
    else:           
        mydict[s.count(word)] += 1

此代码非常慢,部分原因是由于缺乏性能改进以及Python在本质上的性质非常慢。

改善上述代码的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

您可以使用Counter,这就是它们的用途

from collections import Counter
print Counter(Counter(test).values())

例如,

test = ["the", "sun", "rises", "in", "the", "sun"]
from collections import Counter
print Counter(test)
print Counter(Counter(test).values())

<强>输出

Counter({'sun': 2, 'the': 2, 'rises': 1, 'in': 1})
Counter({1: 2, 2: 2})

答案 1 :(得分:1)

您对测试中的每个单词重复计数迭代,增加了if word not in s单词查找的开销。改进可能是计算一次计数:

from collections import Counter
counts = Counter(s)
然后在第二遍中获得hystogram:

distribution = Counter(counts[v] for v in set(test))

演示:

>>> test = list('abcdef')
>>> s = list('here comes the sun')
>>> counts = Counter(s)
>>> distribution = Counter(counts[v] for v in set(test))
>>> distribution
Counter({0: 4, 1: 1, 4: 1})