How to count the frequency of the elements in a li

2018-12-31 09:06发布

I need to find the frequency of elements in a list

a = [1,1,1,1,2,2,2,2,3,3,4,5,5]

output->

b = [4,4,2,1,2]

Also I want to remove the duplicates from a

a = [1,2,3,4,5]

24条回答
只若初见
2楼-- · 2018-12-31 09:18

I would simply use scipy.stats.itemfreq in the following manner:

from scipy.stats import itemfreq

a = [1,1,1,1,2,2,2,2,3,3,4,5,5]

freq = itemfreq(a)

a = freq[:,0]
b = freq[:,1]

you may check the documentation here: http://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.stats.itemfreq.html

查看更多
谁念西风独自凉
3楼-- · 2018-12-31 09:19
num=[3,2,3,5,5,3,7,6,4,6,7,2]
print ('\nelements are:\t',num)
count_dict={}
for elements in num:
    count_dict[elements]=num.count(elements)
print ('\nfrequency:\t',count_dict)
查看更多
爱死公子算了
4楼-- · 2018-12-31 09:20
#!usr/bin/python
def frq(words):
    freq = {}
    for w in words:
            if w in freq:
                    freq[w] = freq.get(w)+1
            else:
                    freq[w] =1
    return freq

fp = open("poem","r")
list = fp.read()
fp.close()
input = list.split()
print input
d = frq(input)
print "frequency of input\n: "
print d
fp1 = open("output.txt","w+")
for k,v in d.items():
fp1.write(str(k)+':'+str(v)+"\n")
fp1.close()
查看更多
墨雨无痕
5楼-- · 2018-12-31 09:20

Yet another solution with another algorithm without using collections:

def countFreq(A):
   n=len(A)
   count=[0]*n                     # Create a new list initialized with '0'
   for i in range(n):
      count[A[i]]+= 1              # increase occurrence for value A[i]
   return [x for x in count if x]  # return non-zero count
查看更多
呛了眼睛熬了心
6楼-- · 2018-12-31 09:21

Since the list is ordered you can do this:

a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
from itertools import groupby
[len(list(group)) for key, group in groupby(a)]

Output:

[4, 4, 2, 1, 2]
查看更多
皆成旧梦
7楼-- · 2018-12-31 09:21

This answer is more explicit

a = [1,1,1,1,2,2,2,2,3,3,3,4,4]

d = {}
for item in a:
    if item in d:
        d[item] = d.get(item)+1
    else:
        d[item] = 1

for k,v in d.items():
    print(str(k)+':'+str(v))

# output
#1:4
#2:4
#3:3
#4:2

#remove dups
d = set(a)
print(d)
#{1, 2, 3, 4}
查看更多
登录 后发表回答