[英]How to cumsum all values at tuple index n, from a list of tuples?
In the following code I want to add second parameters of list=[(0,3),(2,6),(1,10)] in a for loop.在下面的代码中,我想在 for 循环中添加 list=[(0,3),(2,6),(1,10)] 的第二个参数。 first iteration should be 3+6=9 and the second iteration should add output of previous iteration which is 9 to 10---> 9+10=19 and I want final output S=[9,19].第一次迭代应该是 3+6=9,第二次迭代应该添加上一次迭代的输出,即 9 到 10---> 9+10=19,我想要最终输出 S=[9,19]。 I am not sure how to do it, Should I add another loop to my code?我不知道该怎么做,我应该在我的代码中添加另一个循环吗?
T=[(0,3),(2,6),(1,10)]
S=[]
for i in range(len(T)):
b=T[0][i]+T[0][i+1]
S.append(b)
zip
to combine the vales from the tuples
, with the same index.使用zip
组合来自tuples
的值,具有相同的索引。sum
the values in the second tuple
, T[1]
, of T
.使用赋值表达式(从蟒3.8)中,在列表理解,以sum
在第二值tuple
, T[1]
的T
。T = [(0,3),(2,6),(1,10)]
T = list(zip(*T))
print(T)
[out]:
[(0, 2, 1), (3, 6, 10)]
# use an assignment expression to sum T[1]
total = T[1][0] # 3
S = [total := total + v for v in T[1][1:]]
print(S)
[out]:
[9, 19]
use itertools.accumulate使用itertools.accumulate
spam = [(0,3),(2,6),(1,10)]
from itertools import accumulate
print(list(accumulate(item[-1] for item in spam))[1:])
output输出
[9, 19]
This should help u:这应该可以帮助你:
T=[(0,3),(2,6),(1,10)]
lst = [T[i][1] for i in range(len(T))]
final_lst = []
for x in range(2,len(lst)+1):
final_lst.append(sum(lst[:x]))
print(final_lst)
Output:输出:
[9, 19]
If u prefer list comprehension
, then use this line instead of the last for loop
:如果你更喜欢list comprehension
,那么使用这一行而不是最后一个for loop
:
[final_lst.append(sum(lst[:x])) for x in range(2,len(lst)+1)]
Output:输出:
[9, 19]
Just modify your code as below只需修改您的代码如下
T=[(0,3),(2,6),(1,10)]
S=[]
b = T[0][1]
for i in range(1,len(T)):
b+=T[i][1]
S.append(b)
Here is a solution with native recursion这是本机递归的解决方案
import operator
mylist =[(0,3),(2,6),(1,10)]
def accumulate(L, i, op):
def iter(result, rest, out):
if rest == []:
return out
else:
r = op(result, rest[0][i-1])
return iter(r, rest[1:], out + [r])
return iter(L[0][i-1], L[1:], [])
print(accumulate(mylist, 2, operator.add))
print(accumulate(mylist, 1, operator.add))
print(accumulate(mylist, 2, operator.mul))
# ==>
# [9, 19]
# [2, 3]
# [18, 180]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.