如何在Python中使用字典?
10
5
-1
-1
-1
1
1
0
2
...
如果我想统计一个文件中每个数字出现的次数,我该怎么用Python来实现呢?
9 个回答
2
Python 3.1的新特性:
from collections import Counter
with open("filename","r") as lines:
print(Counter(lines))
5
Counter是你最好的朋友哦 :)
这里有关于Counter的详细介绍
如果你用的是Python 2.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})
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"