如何在python中使用dict?

-2 python

10
5
-1
-1
-1
1
1
0
2
...
Run Code Online (Sandbox Code Playgroud)

如果我想计算文件中每个数字的出现次数,我该如何使用python来做呢?

小智 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"
Run Code Online (Sandbox Code Playgroud)


sun*_*ang 5

Counter是你最好的朋友:)
http://docs.python.org/dev/library/collections.html#counter-objects

for(Python2.5 and 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'])
Run Code Online (Sandbox Code Playgroud)

为了这 :

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})
Run Code Online (Sandbox Code Playgroud)