如何删除nd数组中所有不必要的数组 [英] How to remove all unnecessary arrays in nd array

查看:56
本文介绍了如何删除nd数组中所有不必要的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 nd python 数组(不是一个 numpy 数组),它看起来像这样

[[[1,2,3], [4,5,6]]]

我希望能够删除所有不必要的数组,以便我最终得到

[[1,2,3], [4,5,6]]

我写了一个函数来处理这个

def remove_unnecessary(array:list) ->列表:为真:尝试:数组 = *数组除了类型错误:返回数组

但是这不起作用,这主要是因为我缺乏使用带星号的表达式来展开列表的知识.有没有人知道我如何解决这个问题,或者我如何更好地在这个函数中使用 *?

解决方案

你可以一直迭代直到你没有到达内部元素.示例:

<预><代码>>>>def remove_unnecessary(l):...而 len(l) == 1 和 isinstance(l[0], list):... l=l[0]...返回我...>>>remove_unnecessary([[[1,2,3], [4,5,6]]])[[1, 2, 3], [4, 5, 6]]>>>remove_unnecessary([[[[[1,2,3], [4,5,6]]]]])[[1, 2, 3], [4, 5, 6]]>>>remove_unnecessary([1])[1]>>>remove_unnecessary([[1]])[1]

I have a nd python array (not a numpy array), and it looks something like this

[[[1,2,3], [4,5,6]]] 

I'd like to be able to remove all the unnecessary arrays so that I end up with

[[1,2,3], [4,5,6]]

And I wrote a function to handle this

def remove_unnecessary(array:list) -> list:
    while True:
        try:
            array = *array
        except TypeError:
            return array

However this doesn't work, and that's mainly due to my lack of knowledge on using starred expressions to unwrap lists. Does anyone have an idea on how I could fix this or how I could better use * in this function?

解决方案

You can just iterate until you don't reach the inner elements. Example:

>>> def remove_unnecessary(l):
...     while len(l) == 1 and isinstance(l[0], list):
...             l=l[0]
...     return l
... 
>>> remove_unnecessary([[[1,2,3], [4,5,6]]])
[[1, 2, 3], [4, 5, 6]]
>>> remove_unnecessary([[[[[1,2,3], [4,5,6]]]]])
[[1, 2, 3], [4, 5, 6]]
>>> remove_unnecessary([1])
[1]
>>> remove_unnecessary([[1]])
[1]

这篇关于如何删除nd数组中所有不必要的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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