【发布时间】:2017-04-26 01:47:18
【问题描述】:
给定输入:
x = ['foo bar', 'bar blah', 'black sheep']
我可以这样做来获取空格分隔字符串列表中每个单词的计数:
from itertools import chain
from collections import Counter
c = Counter(chain(*map(str.split, x)))
或者我可以简单地遍历并得到:
c = Counter()
for sent in x:
for word in sent.split():
c[word]+=1
[出]:
Counter({'bar': 2, 'sheep': 1, 'blah': 1, 'foo': 1, 'black': 1})
问题是如果输入的字符串列表非常大,哪个效率更高?还有其他方法可以实现相同的计数器对象吗?
假设它是一个文本文件对象,有数十亿行,每行 10-20 个单词。
【问题讨论】:
-
假设每个
sent的大小合理,您的第二个解决方案应该尽可能好。当然,您可以手动遍历字符,但我认为这没有任何改进。我对链子不够熟悉,不知道它在这里的表现如何。 -
你为什么不计时看看?
标签: python dictionary counter itertools chain