how to use list name from string variable

2019-06-02 19:41发布

问题:

I am generating these 2 lists using list comprehension.

lists = ['month_list', 'year_list']
for values in lists:
    print [<list comprehension computation>]

>>> ['2012', '2011', '2010', '2009', '2008', '2007', '2006', '2005', '2004', '2003']
>>> ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']

I want to append these 2 dynamically generated lists to this list names.
for example :

month_list = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']  
year_list = ['2012', '2011', '2010', '2009', '2008', '2007', '2006', '2005', '2004', '2003']

回答1:

month_list = []
year_list = []
lists = [month_list, year_list]
dict = {0 : year_list, 1:month_list}

for i, values in enumerate(data[:2]):
    dict[i].append(<data>)

print 'month_list - ', month_list[0]
print 'year_list - ', year_list[0]

>>> month_list -  ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
>>> year_list -  ['2012', '2011', '2010', '2009', '2008', '2007', '2006', '2005', '2004', '2003']


回答2:

Sounds to me like you should be using references instead of names.

lists = [month_list, year_list]

But list comprehensions can only create a single list regardless, so you'll need to rethink your problem.



回答3:

You can add global variables to the modul's namespace and connect values to them with this method:

globals()["month_list"] = [<list comprehension computation>]

Read more about namespaces in Python documents.

Or you can store these list in a new dictionary.

your_dictionary = {}
your_dictionary["month_list"] = [<list comprehension computation>]


回答4:

Why use strings in the first place?

Why not just do...

lists = [month_list, year_list]
for list_items in lists:
    print repr(list_items)

after you define the two lists?