Python循环改进

2024-03-28 12:26:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何根据另一个数组中的单词来计算数组中单词的分布。你知道吗

我们得到了单词的数组test,任务是将test中出现的单词聚合到新数组s

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

这段代码非常慢,部分原因是缺乏性能改进,以及itetations中Python的特性非常慢。你知道吗

改进上述代码的最佳方法是什么?你知道吗


Tags: 代码intestforifcountnot原因
2条回答

您可以使用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})

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

from collections import Counter
counts = Counter(s)

然后在第二次传球中得到头颅图:

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})

相关问题 更多 >