I'd like to flatten lists that may contain other lists without breaking strings apart. For example:
In [39]: list( itertools.chain(*["cat", ["dog","bird"]]) )
Out[39]: ['c', 'a', 't', 'dog', 'bird']
and I would like
['cat', 'dog', 'bird']
To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.
Now that you know what a Python list of lists is, let’s see how we can use a Python for-loop to flatten them! In our for-loop, we’ll loop over each item in the list and add each item to a new list. We looped over each item, or list, in the list of lists and added each item’s values to our flat_list
Last but not least, there is a one-liner trick you can use to flatten an array in python. With the introduction of list comprehension techniques, you can initialize an array in a single line using for loops. As we have a 2-d array, we’ll use 2 for loops inside a single line in a list comprehension.
This continues onwards, as we add more and more layers. When you convert a list of lists, or a 2-dimensional array, into a one-dimensional array, you are flattening a list of lists. Learn four different ways to do this in this tutorial!
Importing itertools to your python program gives you access to its in-built function called itertools.chain (), which merges various lists of the nested list into a unified list. The 2-D list to be flattened is passed as an argument to the itertools.chain () function. 7. Flatten List in Python Using Reduce Function:
def flatten(foo):
for x in foo:
if hasattr(x, '__iter__') and not isinstance(x, str):
for y in flatten(x):
yield y
else:
yield x
def flatten(foo):
for x in foo:
if hasattr(x, '__iter__'):
for y in flatten(x):
yield y
else:
yield x
(In Python 2.x, strings conveniently didn't actually have an __iter__
attribute, unlike pretty much every other iterable object in Python. Note however that they do in Python 3, so the above code will only work in Python 2.x.)
A slight modification of orip's answer that avoids creating an intermediate list:
import itertools
items = ['cat',['dog','bird']]
itertools.chain.from_iterable(itertools.repeat(x,1) if isinstance(x,str) else x for x in items)
a brute force way would be to wrap the string in its own list, then use itertools.chain
>>> l = ["cat", ["dog","bird"]]
>>> l2 = [([x] if isinstance(x,str) else x) for x in l]
>>> list(itertools.chain(*l2))
['cat', 'dog', 'bird']
def squash(L):
if L==[]:
return []
elif type(L[0]) == type(""):
M = squash(L[1:])
M.insert(0, L[0])
return M
elif type(L[0]) == type([]):
M = squash(L[0])
M.append(squash(L[1:]))
return M
def flatten(L):
return [i for i in squash(L) if i!= []]
>> flatten(["cat", ["dog","bird"]])
['cat', 'dog', 'bird']
Hope this helps
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