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:24
from collections import OrderedDict
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
def get_count(lists):
    dictionary = OrderedDict()
    for val in lists:
        dictionary.setdefault(val,[]).append(1)
    return [sum(val) for val in dictionary.values()]
print(get_count(a))
>>>[4, 4, 2, 1, 2]

To remove duplicates and Maintain order:

list(dict.fromkeys(get_count(a)))
>>>[4, 2, 1]
查看更多
其实,你不懂
3楼-- · 2018-12-31 09:26

In Python 2.7+, you could use collections.Counter to count items

>>> a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
>>>
>>> from collections import Counter
>>> c=Counter(a)
>>>
>>> c.values()
[4, 4, 2, 1, 2]
>>>
>>> c.keys()
[1, 2, 3, 4, 5]
查看更多
浅入江南
4楼-- · 2018-12-31 09:28
seta = set(a)
b = [a.count(el) for el in seta]
a = list(seta) #Only if you really want it.
查看更多
浅入江南
5楼-- · 2018-12-31 09:29

You can use the in-built function provided in python

l.count(l[i])


  d=[]
  for i in range(len(l)):
        if l[i] not in d:
             d.append(l[i])
             print(l.count(l[i])

The above code automatically removes duplicates in a list and also prints the frequency of each element in original list and the list without duplicates.

Two birds for one shot ! X D

查看更多
荒废的爱情
6楼-- · 2018-12-31 09:29
a=[1,2,3,4,5,1,2,3]
b=[0,0,0,0,0,0,0]
for i in range(0,len(a)):
    b[a[i]]+=1
查看更多
爱死公子算了
7楼-- · 2018-12-31 09:30

Counting the frequency of elements is probably best done with a dictionary:

b = {}
for item in a:
    b[item] = b.get(item, 0) + 1

To remove the duplicates, use a set:

a = list(set(a))
查看更多
登录 后发表回答