2

I have a list

[["Sunday", 7, 0], ["Sunday", 2, 0], ["Monday", 1, 5], ["Tuesday", 5, 0], ["Thursday", 2, 0], ["Friday", 3, 0], ["Friday", 1, 0], ["Saturday", 4, 0], ["Monday", 8, 0], ["Monday", 1, 0], ["Tuesday", 1, 0], ["Tuesday", 2, 0], ["Wednesday", 0, 5]]

Can I add the values in the lists to get sums like

["I dont need this value", 37, 10]
2
  • I presume the 100 and the 60 are just some arbitrary examples, and not the actual results you expects for the list in your question? Commented Feb 7, 2012 at 8:20
  • Yes those are arbitrary numbers Commented Feb 7, 2012 at 8:23

5 Answers 5

8

This is precisely what reduce() is made for:

In [4]: reduce(lambda x,y:['',x[1]+y[1],x[2]+y[2]], l)
Out[4]: ['', 37, 10]

where l is your list.

This traverses the list just once, and naturally lends itself to having different -- possibly more complicated -- expressions for computing the three terms.

Sign up to request clarification or add additional context in comments.

2 Comments

Please if you don't mind i want to ask one more question to you, either on chat or anything
Why not ask your question here so everybody can participate?
5

For a flexible number of values per item and even less characters, you can use

In [1]: [sum(values) for values in zip(*l)[1:]]
Out[1]: [37, 10]

zip yields tuples of combinations of corresponding items (i.e. a tuple with all the 1st items, a tuple with all the 2nd items, etc), which can be summed up each (except for the first string value). Of course, you can still prepend "" or whatever you like at the beginning if needed.

Comments

4

I assign your list to l:

l = [ your list .... ]
['dont needed', sum( [ x[1] for x in l ] ), sum(  [x[2] for x in l ] ) ]

Result:

['dont needed', 37, 10]

Comments

4

of course, the ultimate:

>>> stuff=[["Sunday", 7, 0], ["Sunday", 2, 0], ["Monday", 1, 5], ["Tuesday", 5, 0], ["Thursday", 2, 0], ["Friday", 3, 0], ["Friday", 1, 0], ["Saturday", 4, 0], ["Monday", 8, 0], ["Monday", 1, 0], ["Tuesday", 1, 0], ["Tuesday", 2, 0], ["Wednesday", 0, 5]]
>>> stuff=zip(*stuff)
>>> map(sum,stuff[1:])
[37, 10]

Comments

3
>>> stuff=[["Sunday", 7, 0], ["Sunday", 2, 0], ["Monday", 1, 5], ["Tuesday", 5, 0], ["Thursday", 2, 0], ["Friday", 3, 0], ["Friday", 1, 0], ["Saturday", 4, 0], ["Monday", 8, 0], ["Monday", 1, 0], ["Tuesday", 1, 0], ["Tuesday", 2, 0], ["Wednesday", 0, 5]]
>>> sum(j for i,j,k in stuff),sum(k for i,j,k in stuff)
(37, 10)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.