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

后端 未结 3 1989
野趣味
野趣味 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:16

    Just convert the lists to tuple:

    >>> c = Counter(tuple(x) for x in iter(list1))
    >>> c
    Counter({(1.0, 2.66666667, 1.33333333): 3, (1.0, 4.0, 2.5): 2, (1.0, 2.0, 2.0): 1})
    

    Remember to do the same for lookup:

    >>> c[tuple(list1[0])]
    2
    

提交回复
热议问题