Home > database >  Take result from the first loop to run second loop in python
Take result from the first loop to run second loop in python

Time:10-07

I'm trying to run two loops with a set of values. The sum/result from the first loop will be used to run the second loop to obtain the final result. Below is my attempt to do this but we all know why I'm here lol. Any help will be appreciated. Thanks in advance.

loop_input = []
pairSet = [("5", "6", "7"), ("8", "9", loop_input[0])] 
for i, j, k in pairSet:
    sum_values = i   j   k
    loop_input.append(sum_values)

result = loop_input[1]    # The 'sum_values' from the second loop is the desired final result.

CodePudding user response:

The problem is that you are trying to get loop_input[0] before it's set.

You could for example set a placeholder and if in loop you encounter the placeholder you can take the value which is set in the previous run.

Something like this just to give you an idea:

loop_input = []
pairSet = [("5", "6", "7"), ("8", "9", "NA")] 
for index, pair in enumerate(pairSet):
    i, j, k = pair
    if k == "NA":
        k = loop_input[index-1]
    sum_values = i   j   k
    loop_input.append(sum_values)
  • Related