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

4

我想要一个仅包含嵌套列表中第一个元素的列表。嵌套列表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个回答

8
你的解决方案返回了[[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]]

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()...

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接