[英]How do I find the sum of a given list for x[i]≥ a fixed x value, for each x value?
The code block is supposed to do the following:代码块应该执行以下操作:
Find 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)
.查找
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)
。 Find this sum for all x_values in the order given by the list, and append it to a list of its own.按照列表给出的顺序找到所有 x_values 的总和,并将 append 放入它自己的列表中。
The output should be a list with the same length as len(x_values). output 应该是一个与 len(x_values) 长度相同的列表。
For example:例如:
input:输入:
x_values = [1,2,3,3,4,5]
y_values = [9,4,3,1,2,1]
output should be: output 应该是:
[20,11,7,7,3,1]
Note: I'm using python3.注意:我使用的是 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)
You shouldn't be calculating sum(my_list)
every time through the inner loop.您不应该每次都通过内部循环计算
sum(my_list)
。 You should initialize my_list
each time through the outer loop, and calculate the sum after the inner loop.您应该每次通过外循环初始化
my_list
,并在内循环之后计算总和。
However it can all be replaced with a single list comprehension and a generator in the sum()
argument.但是,它可以全部替换为
sum()
参数中的单个列表推导和生成器。
Use zip()
to loop through x_values
and y_values
together, to get the y
values in the corresponding indexes as the x
values that are compared with fixed_x
.使用
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.