[英]How to remove all unnecessary arrays in nd array
我有一個 nd python 數組(不是一個 numpy 數組) ,它看起來像這樣
[[[1,2,3], [4,5,6]]]
我希望能夠刪除所有不必要的數組,以便我最終得到
[[1,2,3], [4,5,6]]
我寫了一個函數來處理這個
def remove_unnecessary(array:list) -> list:
while True:
try:
array = *array
except TypeError:
return array
但是這不起作用,這主要是因為我缺乏使用帶星號的表達式來展開列表的知識。 有沒有人知道我如何解決這個問題或者我如何更好地在這個函數中使用 * ?
您可以迭代,直到您沒有到達內部元素。 例子:
>>> 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]
你可以試試這個:
>>> import numpy as np
>>> l = [[[1,2,3]]]
>>> list(np.array(l).flatten())
[1, 2, 3]
我為此編寫了一個遞歸函數。 讓我知道這是否適合您。
代碼
def list_flatten(example: list) -> list:
try:
if example:
if len(example) > 1:
return example
elif len(example) == 1 and len(example[0]) != 1:
return [elem for element in example for elem in element]
elif len(example) == 1 and len(example[0]) == 1:
return list_flatten(example[0])
else:
return "List empty"
except TypeError:
return example
樣本輸入
example_list = [[[[[1,2,3], [4,5,6], [1]]]]]
example_list_test = [1, 3, 4, 5, 6, 7]
empty_example = []
輸出
list_flatten(example_list) gives:
[[1, 2, 3], [4, 5, 6], [1]]
list_flatten(example_list_test) gives:
[1, 3, 4, 5, 6, 7]
list_flatten(empty_example) gives:
'List empty'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.