How do I find the sum of a given list for x[i]≥ a fixed x value, for each x value?

Question:

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). Find this sum for all x_values in the order given by the list, and append it to a list of its own.

  • The output should be a list with the same length as 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:

[20,11,7,7,3,1]

Note: I’m using 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)
Asked By: display_name_1

||

Answers:

You shouldn’t be calculating sum(my_list) every time through the inner loop. You should initialize my_list each time through the outer loop, and calculate the sum after the inner loop.

However it can all be replaced with a single list comprehension and a generator in the sum() argument.

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.

result = [sum(y for x, y in zip(x_values, y_values) if x >= fixed_x) for fixed_x in x_values]
Answered By: Barmar
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.