简体   繁体   English

如何将元组中的一组列表中的第一个值相加?

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

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. 让我们说,同样的例子,但只添加第3和第4列表中的第一个数字。

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. range(x,y)生成一个从x(包含)到y(排除)的整数列表,以及1作为步骤。 If you want to change the range(x, y, step) will do the same but increasing by step. 如果要更改range(x, y, step)将执行相同操作但逐步增加。

You can find the official documentation here 你可以在这里找到官方文档

Or you can do: 或者你可以这样做:

sum(float(close[4]) for close in tickers[30:40])
>>> 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
>>> 

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. 如果要限制每个元素的某些属性,可以在将其提供给链接中发布的代码之前使用filter() 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))

not seen an answer using reduce yet. 还没有看到使用reduce的答案。

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

In essence sum is identical to reduce(int.__add__, list, 0) 本质上sum与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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM