So I have a list of strings MyList=['ID_0','ID_1','ID_2',.....] from which I used an exec function to create a empty list with elements as names i.e. each I have empty lists ID_0=[] and so on. I now want to create a for loop where I take each list by name and append elements to it like
for i in range(len(MyList)):
*magic*
ID_0.append(i)
where with each loop it uses to next list i.e. ID_1,ID_2.... and so on
I wanted to take each string in MyList and change it into a variable name. Like take 'ID_0' and change it into say ID_0 (which is a empty list as defined earlier) and then make a list BigList=[ID_0,ID_1,ID_2,.....] so that I can just call each list from BgList in my for loop but I dont know how
-
You want this: docs.python.org/3/c-api/reflection.html. Reflection is problematic to describe unless you already know what it's called, :)nicomp– nicomp2021年07月30日 13:04:06 +00:00Commented Jul 30, 2021 at 13:04
-
Well, just about everything so far screams "this is a terrible approach", but as a nudge, why can’t you keep using exec?Rich L– Rich L2021年07月30日 13:04:17 +00:00Commented Jul 30, 2021 at 13:04
-
1It looks like you rather need a dictionary with ID_0, ID_1 as keys and set their values to said list.Tranbi– Tranbi2021年07月30日 13:05:15 +00:00Commented Jul 30, 2021 at 13:05
1 Answer 1
A safer way instead of using exec might be to construct a dictionary, so you can safely refer to each list by its ID:
MyList=['ID_0','ID_1','ID_2']
lists = {}
for i, list_id in enumerate(MyList):
lists[list_id] = [i]
Note that using enumerate is more pythonic than range(len(MyList)). It returns tuples of (index, item).
Alternatively, you could also use defaultdict, which constructs a new item in the dictionary the first time it is referenced:
from collections import defaultdict
lists = defaultdict(list)
for i, list_id in enumerate(MyList):
lists[list_id].append(i)