2012-05-09 102 views
1

我正在使用列表理解生成这2个列表。如何从字符串变量中使用列表名称

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'] 

我想将这两个动态生成的列表附加到这个列表名称。
例如:

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

使用动态变量名称是一个巨大的混乱。不要这样做。永远。你不使用PHP。只需将这些列表放在一个字典中,而不是为它们使用单​​独的变量。 – ThiefMaster

+0

'<列表理解计算>是什么样的?因为最好的答案将取决于它。 (尽管它很可能不会包含循环。) – Robin

回答

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'] 
+0

为什么要使用字符串键?为什么不是整数键? – Robin

1

为什么首先使用字符串?

为什么不只是做...

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

后您定义的两个列表?

3

对我来说听起来像你应该使用引用而不是名称。

lists = [month_list, year_list] 

但是列表解析只能创建一个单独的列表,所以你需要重新思考你的问题。

2

您可以添加全局变量到MODUL的命名空间和连接值,他们用这种方法:

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

Read more about namespaces in Python documents.

或者你可以在一个新的字典存储这些列表。

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