如何在长度可变的列表中删除嵌套的最内层 [英] How to remove the innermost level of nesting in a list of lists of varying lengths

查看:106
本文介绍了如何在长度可变的列表中删除嵌套的最内层的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试删除单元素长度列表的列表中最里面的嵌套.您是否知道一种相对简单的方法(转换为NumPy数组就可以了):

I'm trying to remove the innermost nesting in a list of lists of single element length lists. Do you know a relatively easy way (converting to NumPy arrays is fine) to get from:

[[[1], [2], [3], [4], [5]], [[6], [7], [8]], [[11], [12]]]

对此吗?:

[[1, 2, 3, 4, 5], [6, 7, 8], [11, 12]]

此外,我正在尝试执行的实际列表包含日期时间对象,而不是示例中的int.列表的初始集合将具有不同的长度.

Also, the real lists I'm trying to do this for contain datetime objects rather than ints in the example. And the initial collection of lists will be of varying lengths.

或者,如果原始列表中包含nan,也可以,只要输出列表中不存在nan,则每个列表的长度都相同.即

Alternatively, it would be fine if there were nans in the original list so that the length of each list is identical as long as the nans aren't present in the output list. i.e.

[[[1], [2], [3], [4], [5]], 
 [[6], [7], [8], [nan], [nan]], 
 [[11], [12], [nan], [nan], [nan]]]

对此:

[[1, 2, 3, 4, 5], [6, 7, 8], [11, 12]]

推荐答案

如果嵌套始终是一致的,那么这很简单:

If the nesting is always consistent, then this is trivial:

In [2]: import itertools

In [3]: nested = [ [ [1],[2],[3],[4], [5] ], [ [6],[7],[8] ] , [ [11],[12] ] ]

In [4]: unested = [list(itertools.chain(*sub)) for sub in nested]

In [5]: unested
Out[5]: [[1, 2, 3, 4, 5], [6, 7, 8], [11, 12]]

请注意,将add与列表一起使用的解决方案将为您提供O(n ^ 2)性能,其中n是每个子列表中合并的子子列表的数量.

Note, the solutions that leverage add with lists are going to give you O(n^2) performance where n is the number of sub-sublists that are being merged within each sublist.

这篇关于如何在长度可变的列表中删除嵌套的最内层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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