2

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

Community
  • 1
  • 1
user1452494
  • 1,145
  • 5
  • 18
  • 40

2 Answers2

5

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']
Kevin
  • 74,910
  • 12
  • 133
  • 166
2

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)
beiller
  • 3,105
  • 1
  • 11
  • 19
  • The recursive call to `outlist()` appears to be a syntax error – holdenweb Jul 09 '14 at 15:33
  • 1
    -1: This won't flatten correctly if there are tuples, sets, etc. Rather than singling out `list`, you should single out `string`, since it's probably the only iterable you would want to treat specially. – Two-Bit Alchemist Jul 09 '14 at 15:33
  • oops fixed, changed function to append to a list instead of what it originally did (printing) and also updated to check isinstance(string) which is a good idea. – beiller Jul 09 '14 at 15:33