lar*_*ara 3 python list-comprehension list python-2.7
我想要一个仅包含嵌套列表的第一个元素的列表。嵌套列表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
Run Code Online (Sandbox Code Playgroud)
输出是,R= [0, 3, 6, 0, 3, 6, 0, 3, 6]但我想得到一个单独的结果,如:
R= [[0, 3, 6], [0, 3, 6], [0, 3, 6]]
Run Code Online (Sandbox Code Playgroud)
我也尝试过像[[R.append(t[0]) for t in l] for l in L]这样的列表理解[[None, None, None], [None, None, None], [None, None, None]]
怎么了?
您的解决方案返回,[[None, None, None], [None, None, None], [None, None, None]]因为该方法append返回值None。替换它t[0]应该可以解决问题。
您正在寻找的是:
R = [[t[0] for t in l] for l in L]
Run Code Online (Sandbox Code Playgroud)