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:11

Python 2.7+ introduces Dictionary Comprehension. Building the dictionary from the list will get you the count as well as get rid of duplicates.

>>> a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
>>> d = {x:a.count(x) for x in a}
>>> d
{1: 4, 2: 4, 3: 2, 4: 1, 5: 2}
>>> a, b = d.keys(), d.values()
>>> a
[1, 2, 3, 4, 5]
>>> b
[4, 4, 2, 1, 2]
查看更多
余生无你
3楼-- · 2018-12-31 09:11
def frequencyDistribution(data):
    return {i: data.count(i) for i in data}   

print frequencyDistribution([1,2,3,4])

...

 {1: 1, 2: 1, 3: 1, 4: 1}   # originalNumber: count
查看更多
高级女魔头
4楼-- · 2018-12-31 09:12

You can do this:

import numpy as np
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
np.unique(a, return_counts=True)

Output:

(array([1, 2, 3, 4, 5]), array([4, 4, 2, 1, 2], dtype=int64))

The first array is values, and the second array is the number of elements with these values.

So If you want to get just array with the numbers you should use this:

np.unique(a, return_counts=True)[1]
查看更多
谁念西风独自凉
5楼-- · 2018-12-31 09:12
str1='the cat sat on the hat hat'
list1=str1.split();
list2=str1.split();

count=0;
m=[];

for i in range(len(list1)):
    t=list1.pop(0);
    print t
    for j in range(len(list2)):
        if(t==list2[j]):
            count=count+1;
            print count
    m.append(count)
    print m
    count=0;
#print m
查看更多
泪湿衣
6楼-- · 2018-12-31 09:16

This approach can be tried if you don't want to use any library and keep it simple and short!

a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
marked = []
b = [(a.count(i), marked.append(i))[0] for i in a if i not in marked]
print(b)

o/p

[4, 4, 2, 1, 2]
查看更多
浅入江南
7楼-- · 2018-12-31 09:17
from collections import Counter
a=["E","D","C","G","B","A","B","F","D","D","C","A","G","A","C","B","F","C","B"]

counter=Counter(a)

kk=[list(counter.keys()),list(counter.values())]

pd.DataFrame(np.array(kk).T, columns=['Letter','Count'])
查看更多
登录 后发表回答