我正在数一些从文本文件中得到的字符串。我已经这样做了,但我想知道是否有其他的方法,我可以很快找到。以下是我的代码:-
在这里,我首先找到所有的字符串,并将所有这些放在一个列表中。然后,我将创建一个唯一查询列表,然后在使用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 发布于 2015-02-18 07:01:16
你可以用计数器:
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 发布于 2015-02-18 06:59:11
更好的办法是在他们使用字典的时候数一数:
count = {}
for L in open("input.txt"):
count[L] = count.get(L, 0) + 1最后你会得到一本字典,从行到它们各自的计数。
count方法是快速的,因为它是用C实现的,但是仍然必须扫描每个唯一字符串的完整列表,所以您的实现是O(n^2) (考虑所有字符串都不同的最坏情况)。
https://stackoverflow.com/questions/28577734
复制相似问题