Count the frequency of a recurring list — inside a list of lists

后端 未结 3 2030
野趣味
野趣味 2021-01-19 20:30

I have a list of lists in python and I need to find how many times each sub-list has occurred. Here is a sample,

from collections import Counter
list1 = [[ 1         


        
3条回答
  •  青春惊慌失措
    2021-01-19 21:13

    Try this

    list1 = [[ 1., 4., 2.5], [ 1., 2.66666667, 1.33333333], 
             [ 1., 2., 2.], [ 1., 2.66666667, 1.33333333], [ 1., 4., 2.5],
             [ 1., 2.66666667, 1.33333333]]
    
    counter = {}
    for el in list1:
        el = str(el)     #This sorts your hashable part or use tuple(el)
        if el in counter:
            counter[el]+=1
        else:
            counter[el]=1
    
    print(counter)
    

    Should output

    {'[1.0, 2.0, 2.0]': 1, '[1.0, 2.66666667, 1.33333333]': 3, '[1.0, 4.0, 2.5]': 2}
    

提交回复
热议问题