Python:嵌套列表中的第一个元素
我想要一个只包含嵌套列表中第一个元素的列表。
这个嵌套列表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
你想要的输出是一个嵌套列表。你可以像这样“手动”嵌套它们:
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
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]]
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()
...
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]]
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]