[英]How do I find the sum of a given list for x[i]≥ a fixed x value, for each x value?
代码块应该执行以下操作:
查找sum(all y_values in the list if the index corresponding to that y value has an x_value which is ≥ a fixed x_value)
。 按照列表给出的顺序找到所有 x_values 的总和,并将 append 放入它自己的列表中。
output 应该是一个与 len(x_values) 长度相同的列表。
例如:
输入:
x_values = [1,2,3,3,4,5]
y_values = [9,4,3,1,2,1]
output 应该是:
[20,11,7,7,3,1]
注意:我使用的是 python3。
my_list = []
my_list2 = []
for j in range(len(x_values)):
for i in range(len(x_values)):
if x_values[i] >= x_values[j]: #x_values[j] is supposed to be fixed x_value
my_list.append(y_values[i])
my_list2.append(sum(my_list)) #my_list2 is supposed to be such that len(my_list2)=len(x_values)
您不应该每次都通过内部循环计算sum(my_list)
。 您应该每次通过外循环初始化my_list
,并在内循环之后计算总和。
但是,它可以全部替换为sum()
参数中的单个列表推导和生成器。
使用zip()
将x_values
和y_values
一起循环,以获取相应索引中的y
值作为与fixed_x
比较的x
值。
result = [sum(y for x, y in zip(x_values, y_values) if x >= fixed_x) for fixed_x in x_values]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.