1

I'm trying to add a number of variables, each a numpy array:

x = sum(d1 + d2 + d3 + d4... etc...)

Is there a way to just specify any variables with that string - d plus whatever number - should be included? Maybe there's a simple, slicing-style option? something like:

x = sum(d[1:])

In terms of creating a list, I would still have to compile all the arrays into a list, so my initial question - how to combine them based on name - still stands.

  • 4
    Is there a reason why `d` isn't a list? – Sayse Oct 22 '20 at 10:06
  • 2
    you can use `locals()` and regex, but as @Sayse said, it is better make a list – בנימין כהן Oct 22 '20 at 10:07
  • i don't think such a thing is exist, and will be really curious to see it, but it seems that this is what lists and dictionaries built for... – adir abargil Oct 22 '20 at 10:08
  • Does this answer your question? [How to get the value of a variable given its name in a string?](https://stackoverflow.com/questions/9437726/how-to-get-the-value-of-a-variable-given-its-name-in-a-string) – Tomerikoo Oct 22 '20 at 10:23
  • Thanks for the replies. I edited my q to note that the variables are numpy arrays, not individual values, so I'd still have to combine them somehow. – Matthew Justin Oct 22 '20 at 10:49

3 Answers3

0

Just make d a list

d = [d1, d2, ...]

def dval(num):
return d[num]

def dsum(lwr, upr, stp=1):
return sum(d[lwr:upr:stp])
Alec
  • 8,529
  • 8
  • 37
  • 63
0

as @בינימין כהן said you can use locals() for this specific task even tought it is more recommended to use lists in this scenario, use it just like this for your case:

your_d_vars = [val for key,val in  locals().items() if key[0] == 'd' and key[1:].isdigit()]
x = sum(your_d_vars )
adir abargil
  • 5,495
  • 3
  • 19
  • 29
0

According to this thread, you can, in fact, obtain a variable by a string. As such, you could do something such as the following:

d1 = 4
d2 = 5
d3 = 6
d4 = 7

sum = 0
for i in range(1, 5):
    sum += globals()['d'+str(i)] # build string of the variables you want to access

print(sum) # prints 22

Note: d1, d2, d3, d4 ... must be global variables. Please see the linked thread for more information and other options if necessary.

Matthew Knill
  • 252
  • 2
  • 7
  • If the answer exists in another question already, it should be flagged as a duplicate (as I already did...) – Tomerikoo Oct 22 '20 at 10:25