Reputation: 143
I have a db query that returns tuple as below
[6,6,6,5,5,5,4,4]
[10,10,10,11,11,11]
[3597590, 3597588,3597558,3597544,3597590]
I would like to get the average of each set. I tried to sum them using different ways for example
for row in cur.fetchall(
x = row[4]
print map(sum, x)
it throws an error TypeError: unsupported operand type(s) for +: 'int' and 'str'
I try to convert to int but also throws error ValueError: invalid literal for int() with base 10: '['
Upvotes: 0
Views: 666
Reputation: 226604
The answer from @Copperfield is likely the right way to do it for the problem as stated.
That said, I think you should deal with the problem upstream rather than in Python. Use the SQL SUM and AVERAGE functions inside your query so that the work is done by the SQL engine.
Upvotes: 1
Reputation: 8520
looks like you have a string representing a list of integers, in that case you can use the ast module, more precisely the ast.literal_eval function to transform it to an actual list and sum it
>>> import ast
>>> test = "[3597590, 3597588,3597558,3597544,3597590]"
>>> x=ast.literal_eval(test)
>>> x
[3597590, 3597588, 3597558, 3597544, 3597590]
>>> sum(x)
17987870
>>>
if what you get is a string that looks as your example, then you can use the splitlines method to get each line
>>> test2="""[6,6,6,5,5,5,4,4]
[10,10,10,11,11,11]
[3597590, 3597588,3597558,3597544,3597590]"""
>>> lines = test2.splitlines()
>>> lines
['[6,6,6,5,5,5,4,4]', '[10,10,10,11,11,11]', '[3597590, 3597588,3597558,3597544,3597590]']
>>> map(sum,map(ast.literal_eval,lines))
[41, 63, 17987870]
>>>
as mention in the comments, the json module is another option
>>> import json
>>> test
'[3597590, 3597588,3597558,3597544,3597590]'
>>> json.loads(test)
[3597590, 3597588, 3597558, 3597544, 3597590]
>>>
Upvotes: 2