10
5
-1
-1
-1
1
1
0
2
...
如果我想计算文件中每个数字的出现次数,我该如何使用python来实现呢?
答案 0 :(得分:7)
这几乎与Anurag Uniyal的答案中描述的算法完全相同,只是使用文件作为迭代器而不是readline()
:
from collections import defaultdict
try:
from io import StringIO # 2.6+, 3.x
except ImportError:
from StringIO import StringIO # 2.5
data = defaultdict(int)
#with open("filename", "r") as f: # if a real file
with StringIO("10\n5\n-1\n-1\n-1\n1\n1\n0\n2") as f:
for line in f:
data[int(line)] += 1
for number, count in data.iteritems():
print number, "was found", count, "times"
答案 1 :(得分:5)
柜台是你最好的朋友:) http://docs.python.org/dev/library/collections.html#counter-objects
for(Python2.5和2.6)http://code.activestate.com/recipes/576611/
>>> cnt = Counter()
>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
... cnt[word] += 1
>>> cnt
Counter({'blue': 3, 'red': 2, 'green': 1})
# or just cnt = Counter(['red', 'blue', 'red', 'green', 'blue', 'blue'])
为此:
print Counter(int(line.strip()) for line in open("foo.txt", "rb"))
##output
Counter({-1: 3, 1: 2, 0: 1, 2: 1, 5: 1, 10: 1})
答案 2 :(得分:2)
将文件行读入列表l
,例如:
l = [int(line) for line in open('filename','r')]
从值l
列表开始,您可以创建一个字典d
,为列表中的每个值提供如下所示的出现次数:
>>> l = [10,5,-1,-1,-1,1,1,0,2]
>>> d = dict((x,l.count(x)) for x in l)
>>> d[1]
2
编辑:正如马修正确指出的那样,这不是最佳选择。这是一个使用defaultdict的版本:
from collections import defaultdict
d = defaultdict(int)
for line in open('filename','r'):
d[int(line)] += 1
答案 3 :(得分:2)
我认为你所谓的地图在python中是一本字典 以下是有关如何使用它的一些有用链接:http://docs.python.org/tutorial/datastructures.html#dictionaries
要获得一个好的解决方案,请参阅Stephan或Matthew的答案 - 但也需要一些时间来了解该代码的作用: - )
答案 4 :(得分:2)
Python 3.1中的新功能:
from collections import Counter
with open("filename","r") as lines:
print(Counter(lines))
答案 5 :(得分:1)
答案 6 :(得分:1)
使用字典,其中每一行都是一个键,count是值。每行的增量计数,如果没有行的字典条目,则在except子句中使用1初始化它 - 这应该适用于旧版本的Python。
def count_same_lines(fname):
line_counts = {}
for l in file(fname):
l = l.rstrip()
if l:
try:
line_counts[l] += 1
except KeyError:
line_counts[l] = 1
print('cnt\ttxt')
for k in line_counts.keys():
print('%d\t%s' % (line_counts[k], k))
答案 7 :(得分:0)
l = [10,5,-1,-1,-1,1,1,0,2]
d = {}
for x in l:
d[x] = (d[x] + 1) if (x in d) else 1
原始列表中的每个不同值都会有一个键,d的值将是出现次数。
答案 8 :(得分:0)
#!/usr/bin/env python
import fileinput
from collections import defaultdict
frequencies = defaultdict(int)
for line in fileinput.input():
frequencies[line.strip()] += 1
print frequencies
示例:
$ perl -E'say 1*(rand() < 0.5) for (1..100)' | python counter.py
defaultdict(<type 'int'>, {'1': 52, '0': 48})