How to count number of unique lists within list?

后端 未结 4 477
心在旅途
心在旅途 2021-01-27 12:10

I\'ve tried using Counter and itertools, but since a list is unhasable, they don\'t work.

My data looks like this: [ [1,2,3], [2,3,4], [1,2,3] ]

I would like to

4条回答
  •  生来不讨喜
    2021-01-27 12:21

    >>> from collections import Counter
    >>> li=[ [1,2,3], [2,3,4], [1,2,3] ]
    >>> Counter(str(e) for e in li)
    Counter({'[1, 2, 3]': 2, '[2, 3, 4]': 1})
    

    The method that you state also works as long as there are not nested mutables in each sublist (such as [ [1,2,3], [2,3,4,[11,12]], [1,2,3] ]:

    >>> Counter(tuple(e) for e in li)
    Counter({(1, 2, 3): 2, (2, 3, 4): 1})
    

    If you do have other unhasable types nested in the sub lists lists, use the str or repr method since that deals with all sub lists as well. Or recursively convert all to tuples (more work).

提交回复
热议问题