0

I want to automate this process of assigning variables on every single item in this chart, based on its location. for example the first data point of the first row is named row_1_1, the second data point of the first row is named row_1_2.

As I can think of so far is to break this chart row by row using for loops, and assign them with a variable following the name numerical naming trend like var[n] for n in range(0,5) and then replica this process again inside of a single row to name them individually. So far the working way is to name them in the dummy way but I want to automate this process.

row_1, row_2, row_3, row_4, row_5 = [dataset_in_list[i] for i in range(0, 5)]

row_1_1, row_1_2, row_1_3 = [row_1[x] for x in range(0, 3)]

enter image description here

  • See [Why should I not upload images of code/data/errors?](https://meta.stackoverflow.com/a/285557/3280538) – flakes Apr 24 '23 at 04:20
  • "How to assign a series of variables that follows a numeric naming trend using FOR loops to every single item in a list?" Don't. There is *no good reason to do that* – juanpa.arrivillaga Apr 24 '23 at 04:44

1 Answers1

-1

You'll want to use the globals() object. This function returns the dictionary that stores all the global variables.

In your case, you can use it as follows:

# assign every value in the "dataset_in_list" list to a corresponding variable
for i in range(len(dataset_in_list)):
    for j in range(len(dataset_in_list[i])):
        globals()["row_{}_{}".format(i, j)] = dataset_in_list[i][j]

Note: this does not work for any nested list structure, it only works for a list of lists of values. This only serves as a demonstration of how to use the globals() object in your specific example. For a more general solution of any structure with nested arrays, see below:

myData = [
    [1, 2, 3], ['a', 'b', 'c'], ['asdf', 'ghjkl'], [1.1, 2, 2, "asdf", "lmao"], [[1, 2], [3, [4, 5, 6], 7]]
]

# assign every value in given list to a corresponding variable
def globalize(name, array, iterators):
    for i in range(len(array)):
        if type(array[i]) == type([]):
            globalize(name, array[i], iterators+[i])
        else:
            varname = name
            for iterator in iterators:
                varname += "_{}".format(iterator)
            varname += "_{}".format(i)
            globals()[varname] = array[i]


globalize("row", myData, [])
print(row_4_1_1_2) # 6

Also, note: It's your project, and I've definitely done worse stuff for fun, but for workplace code it's good practice not to decompose an array into the global variables. Just use the array.