Ana Ana - 6 months ago 7
Python Question

how to output the result of a nested loop using Python

I have a function with 3 arguments. I want to calculate that function and output the result for each of the argument combinations.

I have defined my function

F(A,B,C)
, and for now we can assume its output is a single value
f(A,B,C)
.

I then run a nested loop:

for A in range(1,2):
for B in range(4,5):
for C in range(7,8,9):
F(A,B,C)


But it overrides. What I want to get is a dataframe like this:

A B C Output
1 4 7 f(1,4,7)
1 4 8 f(1,4,8)
1 4 9 f(1,4,9)
1 5 7 f(1,5,7)
1 5 8 f(1,5,8)
1 5 9 f(1,5,9)
2 4 7 f(2,4,7)
2 4 8 f(2,4,8)
2 4 9 f(2,4,9)
2 5 7 f(2,5,7)
2 5 8 f(2,5,8)
2 5 9 f(2,5,9)

Answer

range(x,y) does not include the value y

For example range(1,3) contains the numbers [1,2] NOT [1,2,3]

for A in range(1,3):
    for B in range(4,6):
        for C in range(7,10):
            print(A,B,C)

output:

1 4 7
1 4 8
1 4 9
1 5 7
1 5 8
1 5 9
2 4 7
2 4 8
2 4 9
2 5 7
2 5 8
2 5 9

Here's what your ranges were doing

  • range(1,2) --> [1]
  • range(4,5) --> [4]
  • range(7,8,9) --> [7] (This one is even nastier because the third argument is the step value)

As you can see you are just creating 3 ranges with only one item, so when you loop through it never repeats like you want because each range only has one value

That's why your program outputs (1,4,7) then terminates if you change F to print. In my example I increased the second argument of each range by 1 to get the result that you desired.


Making it a dataframe:

listData = []
for A in range(1, 3):
    for B in range(4, 6):
        for C in range(7, 10):
            listData.append([A,B,C, A+B+C]) #I just used A+B+C instead of the func f

df = pandas.DataFrame(columns = ["A", "B", "C", "Output"], data = listData)
print(df)
Comments