2012-05-09 2 views
1

목록 이해를 사용하여이 두 목록을 생성 중입니다.문자열 변수에서 목록 이름을 사용하는 방법

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>] 
관련 문제