I want to use counter function to count for the occurrences of the value 0
for each array inside a list.
from collections import Counter
[Counter(x) for x in a]
[Counter(x)[0] for x in a]
Using the above code it only applies to example like:
a = [array([-2, 0, 0]), array([-2, -1, 1])]
When it applies to the code below which have multiple arrays it raises a TypeError:
a = [[array([-2, 0, 0]), array([-2, -1, 1])], [array([3, -1]), array([1, -2])]]
Expected output:
[[2, 0], [0, 0]]
Can anyone help me?
Counter
cannot magically descend your list and only count the elements in each array independently. It will always act upon the direct iterable you pass to it. In your first example, you iterate your list and then use each element to create a newCounter
; since you have a flat list ofarray
objects, you keep passingarray
objects to the call. In your second example however, you have a list of lists (which then contain array objects). So when you do the same thing as before, you try to create a counter from those lists. So what the counter tries to do is count how often a certain array object appears in that list. But as array objects are not hashable, it cannot identify them and you get that error. But that’s not the logic you want to use anyway.Instead, you want to walk through all your lists and whenever you encounter an array, create a counter from it: