tkyass
tkyass

Reputation: 3186

sum of elements inside python list

I'm trying to write some code that can sum elements inside a list that looks like the following example:

list[(a,b,1),(c,d,2),(e,f,3)]

What I want to do is to sum the numbers inside this list. What is the name of such kind of lists?

Hope you can help me.

Upvotes: 0

Views: 3588

Answers (5)

Vicent
Vicent

Reputation: 5452

Reducing an iterable to a single value is what the built-in reduce function was created for:

In [1]: l = [("a", "b", 1), ("c", "d", 2), ("e", "f", 3)]

In [2]: reduce(lambda x,y: x + y[2], l, 0)
Out[2]: 6

So you don't need to iterate explicitly, the reduce function does it for you. Neither you need to import additional modules.

Upvotes: 0

Rich Tier
Rich Tier

Reputation: 9441

my_list = [('a','b',1),('c','d',2),('e','f',3)]

my_answer = sum(z for x,y,z in my_list)

nice and concise, and very readable for future you. There is no question what is going in here.

Upvotes: 0

Jun HU
Jun HU

Reputation: 3314

you can use func flatten() to parse a nested list like followed list lst = [('a', 'b' , (1, 2)), ('c', 'd' , 2), ('e', 'f', 3)]

def flatten(l):  
    for el in l:  
        if hasattr(el, "__iter__") and not isinstance(el, basestring):  
            for sub in flatten(el):  
                yield sub  
        else:  
            yield el 

print sum(e for e in flatten(lst) if isinstance(e, int))

Upvotes: 0

Abhijit
Abhijit

Reputation: 63737

Given a list, and assuming you have to sum integers as given in the example

foo = [('a','b',1),('c','d',2),('e','f',3)]

You can do the following

sum(e for e in itertools.chain(*foo) if isinstance(e, int))
  • Here itertools.chain would flatten the list
  • isinstance checks if the element is an instance of integer
  • sum only those elements which is an instance of int

Incase if the number elements are at a defined index, as in the example, you can do

>>> zip(*foo)
[('a', 'c', 'e'), ('b', 'd', 'f'), (1, 2, 3)]
>>> sum(zip(*foo)[2])
6

Upvotes: 3

avasal
avasal

Reputation: 14854

try this

it's a list of tuples, you need to iterate over individual elements of the list and extract the value, once extracted you can sum on them

In [103]: l = [('a','b',1),('c','d',2),('e','f',3)]

In [104]: sum([x[2] for x in l])
Out[104]: 6

Upvotes: 3

Related Questions