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

后端 未结 30 3268
时光说笑
时光说笑 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

    #!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()
    

提交回复
热议问题