How to count the frequency of the elements in an unordered list?

后端 未结 30 2906
时光说笑
时光说笑 2020-11-22 02:37

I need to find the frequency of elements in an unordered list

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

output->

b =         


        
相关标签:
30条回答
  • 2020-11-22 02:51

    Another approach of doing this, albeit by using a heavier but powerful library - NLTK.

    import nltk
    
    fdist = nltk.FreqDist(a)
    fdist.values()
    fdist.most_common()
    
    0 讨论(0)
  • 2020-11-22 02:53

    In Python 2.7 (or newer), you can use collections.Counter:

    import collections
    a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
    counter=collections.Counter(a)
    print(counter)
    # Counter({1: 4, 2: 4, 3: 2, 5: 2, 4: 1})
    print(counter.values())
    # [4, 4, 2, 1, 2]
    print(counter.keys())
    # [1, 2, 3, 4, 5]
    print(counter.most_common(3))
    # [(1, 4), (2, 4), (3, 2)]
    

    If you are using Python 2.6 or older, you can download it here.

    0 讨论(0)
  • 2020-11-22 02:54

    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

    0 讨论(0)
  • 2020-11-22 02:55

    Note: You should sort the list before using groupby.

    You can use groupby from itertools package if the list is an ordered list.

    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]
    
    0 讨论(0)
  • 2020-11-22 02:57

    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))
    
    0 讨论(0)
  • 2020-11-22 02:58

    Simple solution using a dictionary.

    def frequency(l):
         d = {}
         for i in l:
            if i in d.keys():
               d[i] += 1
            else:
               d[i] = 1
    
         for k, v in d.iteritems():
            if v ==max (d.values()):
               return k,d.keys()
    
    print(frequency([10,10,10,10,20,20,20,20,40,40,50,50,30]))
    
    0 讨论(0)
提交回复
热议问题