2013-04-23 161 views
3

我有一個程序,有一個嵌套列表,我希望訪問,然後追加到基於條件的新列表。在每個列表中有三個,我希望知道如何分別訪問它們。這是它目前的樣子[['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']]。一個更好解釋這個例子的例子是,如果我想從第二列中獲取數據,那麼我的新列表將看起來像['B', 'E', 'H']將嵌套列表值添加到一個新列表

這是我迄今爲止,但我現在寧願被卡住..

n = 0 
old_list = [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']] 
new_list = [] 

for a, sublist in enumerate(old_list): 
     for b, column in enumerate(sublist): 
       print (a, b, old_list[a][b]) 
       if n == 0: 
        new_list.append(column[0]) 
       if n == 1: 
        new_list.append(column[1]) 
       if n == 2: 
        new_list.append(column[2]) 

print(new_list)   

我的電流輸出..

0 0 A 
0 1 B 
0 2 C 
1 0 D 
1 1 E 
1 2 F 
2 0 G 
2 1 H 
2 2 I 
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'] 

我的期望輸出..

n = 0 
new_list = ['A', 'D', 'G'] 

n = 1 
new_list = ['B', 'E', 'H'] 

n = 2 
new_list = ['C', 'F', 'I'] 

感謝您的幫助!

回答

6
>>> L = [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']] 
>>> columns = list(zip(*L)) 
>>> columns 
[('A', 'D', 'G'), ('B', 'E', 'H'), ('C', 'F', 'I')] 
>>> columns[1] # 2nd column 
('B', 'E', 'H') 

或者,如果你想作爲每列一個清單進行修改(因爲zip收益不變的元組),然後使用:

columns = [list(col) for col in zip(*L)] 
+0

'*'代表什麼? – 2013-04-23 10:24:39

+1

它解開列表到位置參數,一個很好的解釋是在這裏http://stackoverflow.com/questions/2921847/python-once-and-for-all-what-does-the-star-operator-mean-in- python – 2013-04-23 10:25:07

+0

@StephaneRolland它被稱爲「splat」,它將'L'解包爲'zip'的參數 – jamylak 2013-04-23 10:25:39

1

另一種解決方案,它不使用*建設也不zip()

for n in range(3): 
    print('n = {}'.format(n)) 
    new_list = [sublist[n] for sublist in old_list] 
    print('new_list = {}'.format(new_list)) 
相關問題