Dynamically Naming List In Python3
I want to dynamically name the list and use that,I searched a lot but did not get the satisfactory answers how to do that. if __name__=='__main__': lst_2017=[] lst_2018=[
Solution 1:
Use a dictionary instead of naming multiple dynamic variables. Then all your data is in one data structure and easily accessible from key/value pairs.
For the below example I simply zip
up the years and data together to construct a dictionary, where years are the keys and averages are the values.
avg_data = [[1,2,4], [3,4,5], [3,4,6]]
result = {}
for year, avg in zip(range(2017, 2020), avg_data):
result[year] = avg
print(result)
Which can also be done like this, since zip(range(2017, 2020), avg_data)
will give us (year, avg)
tuples, which can be directly translated to our desired dictionary using dict()
:
result = dict(zip(range(2017, 2020), avg_data))
print(result)
Output:
{2017: [1, 2, 4], 2018: [3, 4, 5], 2019: [3, 4, 6]}
You'll probably have to tweak the above to get your desired result, but it shows the general idea.
Solution 2:
Use dictionary with iter:
avg_data = [[1,2,4], [3,4,5], [3,4,6]]
it=iter(avg_data)
d={}
for i in range(2017,2020):
d["lst_"+str(i)]=next(it,None)
for k in d.keys():
print(k, "=",d[k])
Post a Comment for "Dynamically Naming List In Python3"