2012-05-09 50 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>]