1

I am creating an array where most variables are held constant but a couple get looped thru with different values. If i wanted to easily select which two get looped, how would i do that?

Can you use variable names as variables? (Like in PHP) or is there a more pythonic way to write this.

import numpy as np
arrayValues=[]
apple=1
mango=2
banana=3
orange=5
kiwi=10
melon=9
pear=4
applerange=np.linspace(1,50,2)
bananarange=np.linspace(200,700,4)
for apple in applerange:
    for banana in bananarange:
        arrayValues.append([apple, mango, banana, (10-banana), orange, kiwi, melon, pear])
        print('{} and {}'.format(round(apple,2),round(banana,2)))
Nate Houk
  • 335
  • 1
  • 10
  • 4
    Reaching out for this kind of capability seems to be a rite of passage of every new programmers learning journey. However, even in PHP, this is a bad idea. Instead, use a dictionary to hold your values using strings as the keys. https://stackoverflow.com/q/1373164/3141234 – Alexander Jun 06 '22 at 19:37

1 Answers1

0
import numpy as np

variableA = "apple"
variableB = "banana"

arrayValues = []
values = {"apple": 1, "mango": 2, "banana": 3, "orange": 5, "kiwi": 10, "melon": 9, "pear": 4}
ranges = {"apple": np.linspace(1,50,2), "banana": np.linspace(200,700,4)}

for i in ranges[variableA]:
    for j in ranges[variableB]:
        values[variableA] = i
        values[variableB] = j
        arrayValues.append([values["apple"], values["mango"], values["banana"], (10-values["banana"]), values["orange"], values["kiwi"], values["melon"], values["pear"]])
        print('{} and {}'.format(round(values[variableA],2),round(values[variableB],2)))
Nate Houk
  • 335
  • 1
  • 10