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

后端 未结 30 2873
时光说笑
时光说笑 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 03:01
    seta = set(a)
    b = [a.count(el) for el in seta]
    a = list(seta) #Only if you really want it.
    
    0 讨论(0)
  • 2020-11-22 03:01
    #!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()
    
    0 讨论(0)
  • 2020-11-22 03:02

    Found another way of doing this, using sets.

    #ar is the list of elements
    #convert ar to set to get unique elements
    sock_set = set(ar)
    
    #create dictionary of frequency of socks
    sock_dict = {}
    
    for sock in sock_set:
        sock_dict[sock] = ar.count(sock)
    
    0 讨论(0)
  • 2020-11-22 03:04

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

    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

    0 讨论(0)
  • 2020-11-22 03:05

    To count the number of appearances:

    from collections import defaultdict
    
    appearances = defaultdict(int)
    
    for curr in a:
        appearances[curr] += 1
    

    To remove duplicates:

    a = set(a) 
    
    0 讨论(0)
提交回复
热议问题