Update code in deep_flatten
This commit is contained in:
@ -6,25 +6,14 @@ tags: list,recursion,intermediate
|
|||||||
Deep flattens a list.
|
Deep flattens a list.
|
||||||
|
|
||||||
Use recursion.
|
Use recursion.
|
||||||
Define a function, `spread`, that uses either `list.extend()` or `list.append()` on each element in a list to flatten it.
|
Use `isinstance()` with `collections.abc.Iterable` to check if an element is iterable.
|
||||||
Use `list.extend()` with an empty list and the `spread` function to flatten a list.
|
If it is, apply `deep_flatten()` recursively, otherwise return `[lst]`.
|
||||||
Recursively flatten each element that is a list.
|
|
||||||
|
|
||||||
```py
|
```py
|
||||||
def spread(arg):
|
from collections.abc import Iterable
|
||||||
ret = []
|
|
||||||
for i in arg:
|
|
||||||
if isinstance(i, list):
|
|
||||||
ret.extend(i)
|
|
||||||
else:
|
|
||||||
ret.append(i)
|
|
||||||
return ret
|
|
||||||
|
|
||||||
def deep_flatten(lst):
|
def deep_flatten(lst):
|
||||||
result = []
|
return [a for i in lst for a in deep_flatten(i)] if isinstance(lst, Iterable) else [lst]
|
||||||
result.extend(
|
|
||||||
spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst))))
|
|
||||||
return result
|
|
||||||
```
|
```
|
||||||
|
|
||||||
```py
|
```py
|
||||||
|
|||||||
Reference in New Issue
Block a user