Python Forum

Full Version: Counting Number of Element in a smart way
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,
I have an array
[Image: results.png]
I want to count the elements in the array and I can count the number of elements with this code
a0 = sum(np.all((results-np.array([0,0,0]))==0, axis=1))
    x1 = sum(np.all((results-np.array([0,0,1]))==0, axis=1))
    x2 = sum(np.all((results-np.array([0,1,0]))==0, axis=1))
    x3 = sum(np.all((results-np.array([0,1,1]))==0, axis=1))
    x4 = sum(np.all((results-np.array([1,0,0]))==0, axis=1))
    x5 = sum(np.all((results-np.array([1,0,1]))==0, axis=1))
    x6 = sum(np.all((results-np.array([1,1,0]))==0, axis=1))
    x7 = sum(np.all((results-np.array([1,1,1]))==0, axis=1))
But I want to do it in a shorter way. I don't want to specify my all triplets. This time I have 8 different elements so I could write it by hand but if I have 100 different triplets, I couldn't use this code
Is there any nicer way to do it?
Bests
If the only objection is writing out the triplets, you could do the following. It runs the same commands, just does it in a loop.

from itertool import product
triplets = tuple(product((0, 1), repeat = 3))
sums = {}
for triple in triplets:
    sums[triple] = sum(np.all((results-np.array(triple))==0, axis=1))
The sums will be in a dict sums rather than as separate variables. But you can pull them out, or you could change how the keys are named.

However, this doesn't change the fundamental calls made. Perhaps someone else can see if there's a better way to have numpy do the sum more directly.
Thank you very much !