0

I want to iterate over numbered variables (say x1 to x10). For example:

x4=spo.minimize(Agt4,1,method="BFGS").x
x5=spo.minimize(Agt5,1,method="BFGS").x
x6=spo.minimize(Agt6,1,method="BFGS").x

I have over 100 variables like x and Agt. Is there a way to loop over the variables? I don't want to write the code for 100 x and Agt values.

  • 11
    This is definitely a situation where you should be using some kind of aggregate data structure, like a list. – Chris Jan 11 '22 at 17:48
  • 1
    I think this may be an example of [the XY problem](https://meta.stackexchange.com/a/66378). I agree with Chris that this should probably be approached with a list rather than many variables. – NGilbert Jan 11 '22 at 17:50
  • 3
    "I have over 100 variables like x and Agt." That's the problem, you should have never done that. You need to stop thinking in terms of "variables" and start thinking in terms of *data structures*. This sounds like these should have been in a list to begin with, then you just loop over that list. – juanpa.arrivillaga Jan 11 '22 at 17:51
  • 2
    In my opinion `Agt` should be a `list`, and likely so should `x`. Then just use normal array indexing. – Cory Kramer Jan 11 '22 at 17:56
  • 1
    If you had a proper list of `Agt` values, you could write `xs = [spo.minimize(a, 1, method="BFGS").x for a in Agts]` and be done. – chepner Jan 11 '22 at 18:00
  • It's worth noting that the accepted answer to the linked question uses dictionaries, whereas most of the comments here are suggesting lists. For same linked question, I like [this answer](https://stackoverflow.com/a/38972761/9705687), as it (1) uses lists (2) has a more thoughtful discussion on data structures. – bfris Jan 11 '22 at 20:03

0 Answers0