making a flat list out of a list of lists where the elements are strings
Question:
I know a similar question was asked here Making a flat list out of list of lists in Python
But when the elements of the lists are strings, this method does not cut it:
arr = [['i', 'dont'], 'hi']
[item for sublist in arr for item in sublist]
>>['i', 'dont', 'h', 'i']
what I need is:
["I", "dont", "hi"]
thx
Answers:
I know there is a way to do it using your method, but I find that not too readable.
def outlist(li, flatlist):
if isinstance(li, str):
flatlist.append(li)
elif len(li) > 1:
for i in li:
outlist(i, flatlist)
flatlist = []
outlist([['test', 'test2'], 'test3'], flatlist)
print(flatlist)
Modify arr
so that all top-level strings become enclosed in a list. Then the usual list flattening methods will work properly.
arr = [['i', 'dont'], 'hi']
arr = [[item] if isinstance(item, str) else item for item in arr]
#arr is now [['i', 'dont'], ['hi']]
print [item for sublist in arr for item in sublist]
Result:
['i', 'dont', 'hi']
I know a similar question was asked here Making a flat list out of list of lists in Python
But when the elements of the lists are strings, this method does not cut it:
arr = [['i', 'dont'], 'hi']
[item for sublist in arr for item in sublist]
>>['i', 'dont', 'h', 'i']
what I need is:
["I", "dont", "hi"]
thx
I know there is a way to do it using your method, but I find that not too readable.
def outlist(li, flatlist):
if isinstance(li, str):
flatlist.append(li)
elif len(li) > 1:
for i in li:
outlist(i, flatlist)
flatlist = []
outlist([['test', 'test2'], 'test3'], flatlist)
print(flatlist)
Modify arr
so that all top-level strings become enclosed in a list. Then the usual list flattening methods will work properly.
arr = [['i', 'dont'], 'hi']
arr = [[item] if isinstance(item, str) else item for item in arr]
#arr is now [['i', 'dont'], ['hi']]
print [item for sublist in arr for item in sublist]
Result:
['i', 'dont', 'hi']