I would like to generate a list of names corresponding to numbers in the for loop.
For example,
for i in range(10):
for jin range (20):
list_i_j = [i,j]
list_i_j
contains the corresponding number.Alternative alternatives are fine.
Thank you for your cooperation.
python
I don't think there are many situations where it is necessary to assemble variable names in string processing.
You may use it for sh scripts that do not use arrays or associative arrays.
For example, i
and j
are continuous, so I would like to use the list (list of ).
a_list=[ ]
for i in range (10):
child_list = [ ]
a_list.append(child_list)
for jin range (20):
child_list.append([i,j])
# inclusive notation version
a_list = [[[i,j] for jin range(20)] for i in range(10)]
# >>a_list[1][2]
# [1, 2]
If the list is not appropriate and you want to subtract a value from a string like "1_2"
, you should use a dictionary.
a_dic={}
for i in range (10):
for jin range (20):
a_dic [str(i)+"_"+str(j)] = [i,j]
# inclusive notation version
a_dic={str(i)+"_"+str(j): [i,j] for i in range(10) for jin range(20)}
# >>a_dic ["1_2" ]
# [1, 2]
Is it like this?
for i in range(10):
for jin range (20):
exec("list_"+str(i)+"_"+str(j)+"=[i,j]")
# Check the presence of variables
# print globals()
© 2024 OneMinuteCode. All rights reserved.