count occurrences of arrays in multidimensional arrays in python

后端 未结 5 1716
醉酒成梦
醉酒成梦 2020-12-20 18:11

I have the following type of arrays:

a = array([[1,1,1],
           [1,1,1],
           [1,1,1],
           [2,2,2],
           [2,2,2],
           [2,2,2],
         


        
5条回答
  •  清酒与你
    2020-12-20 18:47

    collections.Counter can do this conveniently, and almost like the example given.

    >>> from collections import Counter
    >>> c = Counter()
    >>> for x in a:
    ...   c[tuple(x)] += 1
    ...
    >>> c
    Counter({(2, 2, 2): 3, (1, 1, 1): 3, (3, 3, 0): 3})
    

    This converts each sub-list to a tuple, which can be keys in a dictionary since they are immutable. Lists are mutable so can't be used as dict keys.

    Why do you want to avoid using for loops?

    And similar to @padraic-cunningham's much cooler answer:

    >>> Counter(tuple(x) for x in a)
    Counter({(2, 2, 2): 3, (1, 1, 1): 3, (3, 3, 0): 3})
    >>> Counter(map(tuple, a))
    Counter({(2, 2, 2): 3, (1, 1, 1): 3, (3, 3, 0): 3})
    

提交回复
热议问题