I get an error when adding two values 5 and 5. I would like to receive result 10. I wrote the code based on tuples, this brought me some previous errors because it cannot be add, for example,
sum_A = sum (count_A)
because I received an error
TypeError: unsupported operand type(s) for : 'int' and 'tuple'
So i solved it with sum(int(row[0])
for the row in count_gol_fact_home_sqA
. I didn't like it very much this way. I don't want to use sum_A = sum (int (row [0]) for row in count_A)
However I continued, but I ran into an error that does not make me add sum_A and sum_B.
How can I add sum_A
and sum_B? Is there another way to more easily write my code by previously adding sum_A = sum (count_A)
without receiving errors?
#ELEMENT 1
cursor.execute('SELECT City FROM Nation WHERE X = ?', [X])
count_A = cursor.fetchall() #Print [(2,), (1,), (2,)]
sum_A = sum(int(row[0]) for row in count_A) #print 5
print(sum_A)
###########################################
#ELEMENT 2
cursor.execute('SELECT City FROM Nation WHERE Y = ?', [Y])
count_B = cursor.fetchall() #Print [(3,), (2,)]
sum_B = sum(int(row[0]) for row in count_B) #print 5
print(sum_B)
###########################################
SumA_B = sum(sum_A, sum_B)
print(SumA_B) #ERROR: I would like to get result 10
Error:
Traceback (most recent call last):
File "main.py", line 17, in <module>
SumA_B = sum(sum_A, sum_B)
TypeError: 'int' object is not iterable
CodePudding user response:
sum
expects an iterable, use:
SumA_B = sum([sum_A, sum_B])
CodePudding user response:
Firstly, to fix the error, your problem is that sum
sums the elements of an iterable - not a variable amount of arguments passed to it. So you need to change it to an iterable, like:
sum((sum_A, sum_B))
Or if you only have two items, why not just count_A count_B
?
Then, to simplify your sum
s, you could use itertools.chain
or the more convenient chain.from_iterable
which are used to flatten 2D lists (like you have):
from itertools import chain
sum_A = sum(chain(*count_A))
# Or:
sum_A = sum(chain.from_iterable(count_A))
Lastly, you don't even need to sum A and B separately and sum again the result. Just concatenate them and sum at once:
total_sum = sum(chain.from_iterable(count_A count_B))
Or, in spirit of chaining, you can avoid creating a new list (when doing count_A count_B
) by chaining all the tuples, after chaining the two lists:
total_sum = sum(chain.from_iterable(chain(count_A, count_B)))