0

I need to create something like:

x1 = [1 1 1]
x2 = [2 2 2]
   .
   .
   .
xn = [n n n]

and for this, I was thinking of doing:

for i in range(whatever):
    xi = np.array([i, i, i])

but it doesn't work, obviously. pleasy help me!

mack_hyuuga
  • 11
  • 1
  • 3

4 Answers4

1
x = [np.array([i, i, i]) for i in range(whatever)]

Now x is a nested list and your xi corresponds to x[i]

mattyx17
  • 806
  • 6
  • 11
1

you cant create names or data types or objects like that in python or any other language. use a list object, append to it and you are the person to know that each entry in the list is your "variable Xi":

Use list comprehension

X = [np.array([i, i, i]) for index in range(100)]
Adam
  • 2,820
  • 1
  • 13
  • 33
0

I think you cannot use dynamic variable names in python, but you still can have dynamic dictionary keys. You can use a dictionary to achieve something like this:

data = {}

for i in range(100):
    data['x'+str(i)] = np.array([i, i, i])

Or use the comprehension method

data = {'x{}'.format(i): np.array([i, i, i]) for i in range(100)}

Or using lists:

data = [np.array([i, i, i]) for i in range(100)]
-1

I highly recommend using a dict() or a list(), but what you're trying to do is fairly simple:

for i in range(whatever):
    locals()[f'x{i+1}'] = np.array([i, i, i])



Dictionary:

d = {f'x{i+1}':np.array([i, i, i]) for i in range(whatever)}
Red
  • 26,798
  • 7
  • 36
  • 58