Python: flatten a list of lists, but no more

I have a list of lists that is nested in several layers of lists.

possible inputs:

[[[[1,2,3] , [a,b,c]]]] or [[[1,2,3] , [a,b,c]]] or [[[1,2,3]] , [[a,b,c]]]

when i use flat() it will just smooth out everything i don't want.

[1,2,3,a,b,c]

Instead i need

[[1,2,3] , [a,b,c]]

as the end result.

My flat definition below

 def flat(S): if S == []: return S if isinstance(S[0], list): return flat(S[0]) + flat(S[1:]) return S[:1] + flat(S[1:]) 
+6
source share
3 answers
 import collections def is_listlike(x): return isinstance(x, collections.Iterable) and not isinstance(x, basestring) def flat(S): result = [] for item in S: if is_listlike(item) and len(item) > 0 and not is_listlike(item[0]): result.append(item) else: result.extend(flat(item)) return result tests = [ [[[[1,2,3] , ['a','b','c']]]], [[[1,2,3] , ['a','b','c']]], [[[1,2,3]] , [['a','b','c']]] ] for S in tests: print(flat(S)) 

gives

 [[1, 2, 3], ['a', 'b', 'c']] [[1, 2, 3], ['a', 'b', 'c']] [[1, 2, 3], ['a', 'b', 'c']] 
+7
source

Replacement:

 if S == []: return S 

with:

 if (not any([isinstance(x,list) for x in S])) : return [] if S==[] else [S] 

seems to be doing the trick.

Or:

 if S == []: return S if (not any([isinstance(x,list) for x in S])) : return [S] 

I see two requirements: detecting when S should not be smooth, and then return a value that will not be smoothed when merged with the rest (i.e. connecting to append , not extend ). I assume that the list of items from the list should not be flattened.

I bark the same tree as unutbu , but in a more confusing way. :)

+2
source

flat () can become

 def flat(mylist): return[val for sublist in mylist for val in sublist] 

Then you can call it in a for loop like this

 while type(mylist[0][0]) is list: mylist = flat(my list) 

and it will reduce it to the desired result, regardless of the number of nested lists

 [[1, 2, 3], ['a', 'b', 'c']] 
0
source

Source: https://habr.com/ru/post/980157/


All Articles