Python:嵌套列表中的第一个元素

时间:2014-09-12 10:51:07

标签: python list python-2.7 list-comprehension

我想要一个只包含嵌套列表的第一个元素的列表。 嵌套列表L,它看起来像:

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]]

有什么问题?

5 个答案:

答案 0 :(得分:4)

您的解决方案返回[[None, None, None], [None, None, None], [None, None, None]],因为方法append返回值None。用t[0]替换它应该可以解决问题。

您正在寻找的是:

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

答案 1 :(得分: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]]

答案 2 :(得分:1)

您还可以将numpy数组与转置函数一起使用。

import numpy as np
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]] ]
Lnumpy = np.array(L)
Ltransposed = Lnumpy.transpose(0, 2, 1) # Order of axis

现在输出

[[[0 3 6]
  [1 4 7]
  [2 5 8]]

 [[0 3 6]
  [1 4 7]
  [2 5 8]]

 [[0 3 6]
  [1 4 7]
  [2 5 8]]]

现在,您不需要成员的每个第一个成员。

print(Ltransposed[0][0])现在给您[0, 3, 6] 然后

for i in ltr:
    print(ltr[0][0])

输出

[0 3 6]
[0 3 6]
[0 3 6]

仅此而已,还有可能使用zip ...(这里是Python 3 ...)

print(list(zip(*Ltransposed))[0])

给您相同的感觉。如果您需要列表,请将其转换回... list() ...

答案 3 :(得分: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]]

答案 4 :(得分:0)

您希望输出为嵌套列表。你可以用手捂住它们#34;像这样:

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