Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I flatten lists without splitting strings?

Tags:

python

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']
like image 385
Cev Avatar asked Mar 13 '11 00:03

Cev


People also ask

How do you merge a list into a string in Python?

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.

How do you flatten a list of lists in Python?

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

How to flatten an array in Python in one line?

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.

What does it mean to flatten a list?

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!

How to flatten list in Python using itertools?

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:


Video Answer


4 Answers

Solution:

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

Old version for Python 2.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.)

like image 158
Amber Avatar answered Nov 02 '22 23:11

Amber


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)
like image 45
Geoff Reedy Avatar answered Nov 02 '22 21:11

Geoff Reedy


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']
like image 33
orip Avatar answered Nov 02 '22 21:11

orip


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

like image 25
inspectorG4dget Avatar answered Nov 02 '22 21:11

inspectorG4dget