Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum columns in list with text fields

Tags:

python

sum

Say I've a Python list as below:

list =  [ ['text',2,3,4], ['text2',4,5,6] ]
y= map(sum,zip(*list))
print y 

Gives int /str error.

How would I pop all 'text' in all rows and sum the remaining columns. Ans: Im looking for [6, 8, 10] I noticed that field look like int but are str. 4 vs '4'.

like image 372
Merlin Avatar asked Nov 19 '25 00:11

Merlin


1 Answers

In [111]: lst =  [ ['text',2,3,4], ['text2',4,5,6] ]

In [112]: import operator

In [113]: print(map(operator.add,*lst))
['texttext2', 6, 8, 10]

If you don't know a priori which columns contain text, then you could use a try..except block to handle the text:

lst =  [ ['text',2,3,4], ['text2',4,5,6] ]
result=[]
for column in zip(*lst):
    try:
        result.append(sum(map(int,column)))
    except ValueError:
        pass
print(result)
# [6, 8, 10]
like image 89
unutbu Avatar answered Nov 20 '25 14:11

unutbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!