python - Counting occurrences in a loop -


gzip_files=["complete-credit-ctrl-txn-se06_2013-07-17-00.log.gz","complete-credit-ctrl-txn-se06_2013-07-17-01.log.gz"]  def input_func():     num = input("enter number of min series digits: ")     return num  in gzip_files:     import gzip     f=gzip.open(i,'rb')     file_content=f.read()     digit = input_func()     file_content = file_content.split('[')     series = [] #list of min     line in  file_content:         min = line.split('|')[13:15]         x in min:             n = digit             x = x[:n]             series.append(x)             break       #count number of occurences in list named series     in series:         print     #end count 

result:

63928 63928 63929 63929 63928 63928 

that part of result. actual result shows long list. want list unique numbers , specify how many times showed on list.

63928 = 4,  63929 = 2 

i use collections.counter class here.

>>> = [1, 1, 1, 2, 3, 4, 4, 5] >>> collections import counter >>> counter(a) counter({1: 3, 4: 2, 2: 1, 3: 1, 5: 1}) 

just pass series variable counter , you'll dictionary keys unique elements , values occurences in list.

collections.counter introduced in python 2.7. use following list comprehension versions below 2.7

>>> [(elem, a.count(elem)) elem in set(a)] [(1, 3), (2, 1), (3, 1), (4, 2), (5, 1)] 

you can convert dictionary easy access.

>>> dict((elem, a.count(elem)) elem in set(a)) {1: 3, 2: 1, 3: 1, 4: 2, 5: 1} 

Comments

Popular posts from this blog

javascript - DIV "hiding" when changing dropdown value -

Does Firefox offer AppleScript support to get URL of windows? -

android - How to install packaged app on Firefox for mobile? -