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:])
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 (ie 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.:)
flat() could become
def flat(mylist):
return[val for sublist in mylist for val in sublist]
Then you could 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 your desired output regardless of the number of nested lists
[[1, 2, 3], ['a', 'b', 'c']]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.