I have a list of lists which is nested in multiple 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 flatten everything which is not what I want.
[1,2,3,a,b,c]
What I need instead is
[[1,2,3] , [a,b,c]]
as the final output.
My flat definition is 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:])
Flattening a list of lists entails converting a 2D list into a 1D list by un-nesting each list item stored in the list of lists - i.e., converting [[1, 2, 3], [4, 5, 6], [7, 8, 9]] into [1, 2, 3, 4, 5, 6, 7, 8, 9] .
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))
yields
[[1, 2, 3], ['a', 'b', 'c']]
[[1, 2, 3], ['a', 'b', 'c']]
[[1, 2, 3], ['a', 'b', 'c']]
Replacing:
if S == []:
return S
with:
if (not any([isinstance(x,list) for x in S])) :
return [] if S==[] else [S]
seems to do 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
shouldn't be flattened, and then returning a value that won't be flatten when joined with the rest (i.e. join with append
rather than extend
). My guess is that a list of non-list elements should not be flattened.
I'm barking up the same tree as unutbu
, but in a more confused manner.:)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With