切片多维列表 [英] Slicing a multidimensional list

查看:38
本文介绍了切片多维列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可变长度的多维数据集,如下所示:

I have a variable length multi-dimensional like the following:

listD = [[[[53, 54], [129, 130]]], 
     [[[51, 51], [132, 132]]], 
     [[[39, 39], 
       [144, 144]], 
      [[53, 54], 
       [129, 130]]], 
     [[[39, 39], [146, 146]], [[54, 54], [130, 130]]], 
     [[[54, 53], [130, 129]]], 
     [[[52, 52], [132, 132]]]
    ]

我需要在每个列表的最里面选择第一个元素.输出应如下所示:

I need to pick out the first element in each of the innermost of the lists. The output should look like this:

outlist=[[[[53, 54]]], 
     [[[51, 51]]], 
     [[[39, 39]], 
      [[53, 54]]], 
     [[[39, 39]], 
      [[54, 54]]], 
     [[[54, 53]]], 
     [[[52, 52]]]
    ]

我正在尝试使用0和:s进行切片,但没有得到正确的列表.如何在python中做到这一点?

I am trying to slice using 0 and :s, I am not getting the right list back. How to do this in python?

我的退出清单中有一个错误.我已经编辑了清单.对困惑感到抱歉.

I had made an error in my out list. I have edited the list. Sorry for the confusion.

推荐答案

尝试使用嵌套列表理解:

Try with nested list comprehension:

[[[x[0]] for x in y] for y in listD]


分步进行:

查看您的 listD 中的每个嵌套行,并查看其与 outlist 的对应关系.您可以看到,每个1深列表的第一个元素都包含在 outlist

Look at each nested row in your listD and see how it corresponds to outlist. You can see that the first element of each of the 1-deep list is included in outlist

>>> [x[0] for x in listD[0]] 
[[53, 54]]
>>> [x[0] for x in listD[1]] 
[[51, 51]]
>>> [x[0] for x in listD[2]] 
[[39, 39], [53, 54]]

但是在 outlist 中,这些列表然后嵌套在一个又一个1元素列表中,因此将每个列表包装到自己的列表中,例如,下一个元素将是:

But in outlist, these lists are then nested in one more 1-element list, so wrap each one of these into it's own list, e.g the next element would be:

>>> [[x[0] for x in listD[3]]]
[[[39, 39], [54, 54]]]

然后将其扩展为 listD 的每个索引:

then extend it for each index of listD:

[[[x[0]] for x in listD[i]] for i in range(len(listD))]

然后通过仅用 listD 的元素替换 listD [i] 来进一步简化:

then simplify further by replacing listD[i] with just the elements of listD:

[[[x[0]] for x in y] for y in listD]

这篇关于切片多维列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆