[英]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.