2014-09-12 138 views
0

我想要一个只包含嵌套列表的第一个元素的列表。 嵌套表L,它的样子:Python:嵌套列表中的第一个元素

L =[ [[0,1,2],[3,4,5],[6,7,8]], [[0,1,2],[3,4,5],[6,7,8]], [[0,1,2],[3,4,5],[6,7,8]] ] 

for l in L: 
for t in l: 
    R.append(t[0]) 
print 'R=', R 

输出是R= [0, 3, 6, 0, 3, 6, 0, 3, 6]但我想得到这样一个分离的结果是:

R= [[0, 3, 6], [0, 3, 6], [0, 3, 6]] 

我也通过列表理解试过像[[R.append(t[0]) for t in l] for l in L]但这给出[[None, None, None], [None, None, None], [None, None, None]]

出了什么问题?

回答

2

您的解决方案返回[[None, None, None], [None, None, None], [None, None, None]]因为append返回值None的方法。用t[0]取代它应该可以做到。

什么你要找的是:

R = [[t[0] for t in l] for l in L] 
2

你可以做这样的:

>>> L = [ [[0,1,2],[3,4,5],[6,7,8]], [[0,1,2],[3,4,5],[6,7,8]], [[0,1,2],[3,4,5],[6,7,8]] ] 
>>> R = [ [x[0] for x in sl ] for sl in L ] 
>>> print R 
[[0, 3, 6], [0, 3, 6], [0, 3, 6]] 
+0

@ isedev谢谢! – lara 2014-09-12 11:07:19

0
L =[ [[0,1,2],[3,4,5],[6,7,8]], [[0,1,2],[3,4,5],[6,7,8]], [[0,1,2],[3,4,5],[6,7,8]] ] 
R=[] 
for l in L: 
temp=[] 
for t in l: 
    temp.append(t[0]) 
R.append(temp) 
print 'R=', R 

输出:

R= [[0, 3, 6], [0, 3, 6], [0, 3, 6]] 
0

你所要的输出是一个嵌套列表。您可以嵌套他们“手”是这样的:

L =[ [[0,1,2],[3,4,5],[6,7,8]], [[0,1,2],[3,4,5],[6,7,8]], [[0,1,2],[3,4,5],[6,7,8]] ] 
R = [] 
for l in L: 
    R2 = [] 
    for t in l: 
     r2.append(t[0]) 
    R.append(R2) 
print 'R=', R 
相关问题