计算字符串出现次数的最快方法

时间:2015-02-18 06:55:48

标签: python

我正在计算一些我从文本文件中获取的字符串。我已经这样做但我想知道有没有其他方法可以很快找到。 以下是我的代码: -

首先,我找到所有字符串并将所有这些字符串放入列表中。然后,在我使用count方法查找计数之后,我会创建一个唯一查询列表。

input.txt中

shoes
memory card
earphones
led bulb
mobile
earphones
led bulb
mobile

以上是我的输入文件。

new = []
with open("input.txt") as inf:
for line in inf:
    line = line.strip("\n")
    new.append(line)
unique = list(set(new))
for i in unique:
   cnt = new.count(i)
   print i,cnt

并且输出应如下所示:

   mobile 2
   memory card 1
   led bulb 2
   shoes 1
   earphones 2 

2 个答案:

答案 0 :(得分:3)

你可以使用counter:

from collections import Counter        

with open("input.txt") as inf:
   c = Counter(l.strip() for l in inf)

给出:

Counter({'led bulb': 2, 'earphones': 2, 'mobile': 2, 'memory card': 1, 'shoes': 1})

for k,v in c.items():
    print(k,v)  

给出:

memory card 1
mobile 2
earphones 2
led bulb 2
shoes 1  

答案 1 :(得分:1)

当他们使用字典进行计数时,更好的是计算它们:

count = {}
for L in open("input.txt"):
    count[L] = count.get(L, 0) + 1

你最终会得到一条从字母到各自字数的字典。

count方法很快,因为它在C中实现,但仍然必须扫描每个唯一字符串的完整列表,因此您的实现是O(n ^ 2)(考虑最坏的情况)所有字符串都不同。)

相关问题