How do I sum the first value in a set of lists within a tuple?

◇◆丶佛笑我妖孽 提交于 2019-12-22 18:43:29

问题


Hey, I would like to be able to perform this but with being selective for which lists I sum up. Let's say, that same example, but with only adding up the first number from the 3rd and 4th list.


回答1:


Something like:

sum(int(tuple_list[i][0]) for i in range(3,5))

range(x, y) generates a list of integers from x(included) to y(excluded) and 1 as the step. If you want to change the range(x, y, step) will do the same but increasing by step.

You can find the official documentation here

Or you can do:

sum(float(close[4]) for close in tickers[30:40])



回答2:


>>> l1
[(0, 2), (1, 3), (2, 4), (3, 5), (4, 6), (5, 7), (6, 8), (7, 9), (8, 10), (9, 11)]
>>> sum([el[0] for (nr, el) in enumerate(l1) if nr in [3, 4]])
7
>>> 



回答3:


If you want to limit by some property of each element, you can use filter() before feeding it to the code posted in your link. This will let you write a unique filter depending on what you want. This doesn't work for the example you gave, but it seemed like you were more interested in the general case.

sum(pair[0] for pair in filter(PREDICATE_FUNCTION_OR_LAMBDA, list_of_pairs))



回答4:


not seen an answer using reduce yet.

reduce(lambda sumSoFar,(tuple0,tuple1): sumSoFar+tuple0, list, 0)

In essence sum is identical to reduce(int.__add__, list, 0)

edit: didn't read the predicate part.

Easily fixed, but probably not the best answer anymore:

predicate = lambda x: x == 2 or x == 4
reduce(lambda sumSoFar,(t0,t1): sumSoFar+(t0 if predicate(t0) else 0), list, 0)


来源:https://stackoverflow.com/questions/4663024/how-do-i-sum-the-first-value-in-a-set-of-lists-within-a-tuple

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!