0

I wish to do a summation like this:

tot_males = 0
tot_females = 0
for groups in itertools.chain.from_iterable(self.class): # Iterates over all the class
    current_males, current_females = groups.number_of_persons() # Returns how many males and females there are in one group
    tot_males += current_males
    tot_females += current_females

return tot_males, tot_females # EDIT: Corrected return values

Is there any way to do this summation without a for loop? I am just curious. This is the best solution I have created so far.

Bob Pen
  • 67
  • 6
  • Does this answer your question? [sum each value in a list of tuples](https://stackoverflow.com/questions/14180866/sum-each-value-in-a-list-of-tuples) – azro Jun 10 '20 at 21:03
  • It would give something like `[sum(x) for x in zip(*[g.number_of_persons() for g in itertools.chain.from_iterable(self.class)])]` Also careful your return is wrong you don't return the sum. I'd you could do now directly : `return *[sum(x) for x in zip(*[g.number_of_persons() for g in itertools.chain.from_iterable(self.class)])]` – azro Jun 10 '20 at 21:06
  • Ah yes! My return is wrong! I will fix that. And that is exactly what I was looking for, I tried googling, but didn't google well enough. Thank you very much. – Bob Pen Jun 10 '20 at 21:08
  • You can post it as an answer and I can accept it or I can delete the post, what do you recommend? – Bob Pen Jun 10 '20 at 21:14

3 Answers3

1

Adapting the solution given from sum value of list of tuple You could do the following

return *[sum(x) for x in zip(*[g.number_of_persons() for g in itertools.chain.from_iterable(self.class)])]

Of course it could be splitted for better comprehension

groups = [g.number_of_persons() for g in itertools.chain.from_iterable(self.class)]
sums = [sum(x) for x in zip(*groups)]
tot_males, tot_females = *sums
return tot_males, tot_females
azro
  • 53,056
  • 7
  • 34
  • 70
1

You can do something like this with lambda function and numpy.

pairs = numpy.array(list(map(lambda g: g.number_of_persons(), 
                          itertools.chain.from_iterable(self.class))))

return numpy.sum(pairs, axis=0)
expectedAn
  • 96
  • 9
0

You can accomplish that with the method sum():

return sum[grps.num_of_per()[0] for grps in itertools.chain.from_iterable(self.class)], sum[grps.num_of_per()[1] for grps in chain.from_iterable(self.class)]
Red
  • 26,798
  • 7
  • 36
  • 58