How to sum columns in a list with text fields

Let's say I have a Python list as shown below:

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

Gives an int / str error.

How to put all the text in all rows and summarize the remaining columns. Ans: Im looking for [6, 8, 10] I noticed that the field looks like an int, but str. 4 vs 4 '.

+3
source share
4 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 do not know a priori which columns contain text, you can use the try..except block to process 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]
+4
source
>>> 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]
>>>
+3
source
y = map(lambda x: sum(int(k) for k in x[1:]),
        zip(*list))

If you also expect decimal numbers, you can change it to float()insteadint()

+1
source
def tail(l):
    return l[1:]

map(sum, zip(*map(tail, list))

Note. Lately I've been doing too much Haskell .; -)

0
source

Source: https://habr.com/ru/post/1791376/


All Articles