2013-04-23 153 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))