问题
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?
回答1:
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]
回答2:
You can try this:
>>> import numpy as np
>>> l = [[[1,2,3]]]
>>> list(np.array(l).flatten())
[1, 2, 3]
回答3:
I wrote a recursive function for this. Let me know if this does the job for you.
Code
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
Sample Inputs
example_list = [[[[[1,2,3], [4,5,6], [1]]]]]
example_list_test = [1, 3, 4, 5, 6, 7]
empty_example = []
Outputs
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'
来源:https://stackoverflow.com/questions/60128295/how-to-remove-all-unnecessary-arrays-in-nd-array