I stumble upon some issue with list. I have nested list like this one
[[1, 2, 3], [4, 5, 6],[7, 8, 9]]
This list can be arbitrarily large and inner list does not need to be in the same length(size). What I would like to achieve is to take out each inner list and assign to new variable. This means in our toy example the following.
Var1=[1,2,3]
Var2=[4,5,6]
Var3=[7,8,9]
I can index it manually in toy example each inner list, but this not desired result. I need to store as separate variable each inner list. Moreover I prefer function to do this for me.
What I need is a function that takes nested list and assigns each inner list to variable automatically. Input of function should be nested list and output should be each inner list assign to variable. The solution should scale to larger list size.
-
2is there a reason you want to do this? what makes indexing the original list a problem?python_user– python_user2021年01月31日 12:33:03 +00:00Commented Jan 31, 2021 at 12:33
-
I need to be automatic. I do not want do it manually.vasiop– vasiop2021年01月31日 12:34:27 +00:00Commented Jan 31, 2021 at 12:34
-
ok, can you edit the question saying how assigning to different variables would make your problem easier? as it stands you have not pointed out why indexing is not an optimal approach for youpython_user– python_user2021年01月31日 12:36:41 +00:00Commented Jan 31, 2021 at 12:36
-
@ python_user Done it.vasiop– vasiop2021年01月31日 12:39:49 +00:00Commented Jan 31, 2021 at 12:39
-
You can use a dictionary to solve your problem. Maintain a counter for key and loop through the nested list. That way it will be automatic too.neilharia7– neilharia72021年01月31日 12:43:27 +00:00Commented Jan 31, 2021 at 12:43
1 Answer 1
This should work:
main_list = [[1, 2, 3], [4, 5, 6],[7, 8, 9]]
for i in range(len(main_list)):
declare_statement = f'Var{i} = {main_list[i]}'
exec(declare_statement)
'''
now each value of the main_list is stored in variable different variable with
prefix "Var" and index of that value as postfix
'''
That means print(Var0)
would display [1, 2, 3]
, print(Var1)
would display [4, 5, 6]
and so on but honestly I don't see a point to this.
You could've achieved the same thing by print(main_list[0])
and print(main_list[1])
it is just a waste of memory to assign each value of a list to a variable and it also defeats the purpose of lists and arrays.
-
Thanks. This is what I look for.vasiop– vasiop2021年01月31日 12:58:08 +00:00Commented Jan 31, 2021 at 12:58