Python Forum
Counting Number of Element in a smart way
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Counting Number of Element in a smart way
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?
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.
quest likes this post
Thank you very much !

Possibly Related Threads…
Thread Author Replies Views Last Post
  Counting number of words and organize for the bigger frequencies to the small ones. valeriorsneto 1 261 Feb-05-2021, 03:49 PM
Last Post: perfringo
  Counting Element in Multidimensional List quest_ 1 374 Nov-25-2020, 10:00 PM
Last Post: quest_
  get method not counting number of strings in dictionary LearningTocode 2 545 Jun-13-2020, 11:17 PM
Last Post: LearningTocode
  counting items in a list of number combinations Dixon 2 678 Feb-19-2020, 07:06 PM
Last Post: Dixon
  Counting number of occurrences of a single digit in a list python_newbie09 12 1,969 Aug-12-2019, 01:31 PM
Last Post: perfringo
  How to list number of times element is in defaultdict and delete it mrapple2020 3 995 Apr-15-2019, 07:34 AM
Last Post: perfringo
  Build class to make a Smart list - trying icm63 7 1,205 Mar-28-2019, 08:53 PM
Last Post: icm63
  Adding a line number to an lxml Element vindy 0 1,253 Mar-08-2019, 08:34 PM
Last Post: vindy
  Counting the number of letters in a string alphabetically TreasureDragon 2 1,031 Mar-07-2019, 01:03 AM
Last Post: TreasureDragon
  Unable to locate element no such element gahhon 6 1,569 Feb-18-2019, 02:09 PM
Last Post: gahhon

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020