How to sum columns in list with text fields
Say I've a Pyt开发者_高级运维hon 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'.
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]
>>> map(sum, zip(*list)[1:])
[6, 8, 10]
>>> list = [ ['text','2','3','4'], ['text2','4','5','6'] ]
>>> map(sum , [map(int,i) for i in zip(*list)[1:]] )
[6, 8, 10]
>>>
y = map(lambda x: sum(int(k) for k in x[1:]),
zip(*list))
If you also expect decimals, you can change it to float()
instead of int()
def tail(l):
return l[1:]
map(sum, zip(*map(tail, list))
Note: I have been doing too much Haskell lately. ;-)
精彩评论