Say I have a function, denoted by Show, that runs by accessing points in a list. Is it then possible to assign each outcome from the function to a variable? Is it possible for the variable to be defined by dfi so the outputs would be df1, df2, df3, ect... for a long as defined by count?
count = 5
for i in range(0, count):
d = Show(list[i])
CodePudding user response:
Dynamic naming could be achieved by using advanced Python features not recommended for normal use (see for instance Dynamically set local variable).
If you know the number of elements in advance, you can do
df1, df2, df3, df4, df5 = [Show(list[i]) for i in range(5)]
If you don't, you're probably better off using a list to store the results.
count = 5
d = []
for i in range(0, count):
d.append(Show(list[i]))
which can be more elegantly written
d = [Show(list[i]) for i in range(count)]
or even a dictionary
d = [f"df{i}": Show(list[i]) for i in range(count)]
CodePudding user response:
You can do this using a dict by storing variables as keys. A sample could be like this:
count = 5
dic = {}
for i in range(count):
#create key, that would be the variable
k = "df{}".format(i)
dic[k] = show(list[i])
And now you can use dict to fetch and use the variables in O(1) which would be same as if you have defined the variables explicitly and stored them.