Question

Assuming input:

[1, [3, 6], 9, [2, [1, 3]], [4, [1], 5], [6], 1, [[2]]]

Expected output:

[1,1,1,1,2,2,3,3,4,5,6,6,9]

How do I flatten the list without removing the duplicates?

My current situation

def flatten(lst):
    nlist = []
    for item in lst:
        nlist = nlist + [item]
    return nlist

My initial thought was that to re-add the elements into a new list to get the expected output. However it did not went well, I am getting

What i get:

[1, [3, 6], 9, [2, [1, 3]], [4, [1], 5], [6], 1, [[2]]]

I am using IDLE 3.3, and I am totally a newbie, if it is possible please tell me how to define it manually instead of using built in functions, meaning using recursive or iterative method. thanks guys!!

Was it helpful?

Solution

You can recursively flatten the data like this

>>> def rec(current_item):
...     if type(current_item) == list:
...         for items in current_item:
...             for item in rec(items):
...                 yield item
...     elif type(current_item) == int:
...         yield current_item

and then sort it like this

>>> sorted(rec([1, [3, 6], 9, [2, [1, 3]], [4, [1], 5], [6], 1, [[2]]]))
[1, 1, 1, 1, 2, 2, 3, 3, 4, 5, 6, 6, 9]

OTHER TIPS

From funcy module (https://github.com/Suor/funcy) you can pick flatten function.

In this case, provided that funcy is available on your host, the following code should work as expected:

from funcy import flatten

nlist = [1, [3, 6], 9, [2, [1, 3]], [4, [1], 5], [6], 1, [[2]]]
flat_list = flatten(nlist)

print(nlist)
# [1, [3, 6], 9, [2, [1, 3]], [4, [1], 5], [6], 1, [[2]]]

print(sorted(flat_list))
# [1, 1, 1, 1, 2, 2, 3, 3, 4, 5, 6, 6, 9]

A python 2.* only solution would be using the ast module from the compiler package (not available in python 3 anymore). It fits perfectly with this particular example:

import compiler

a = [1, [3, 6], 9, [2, [1, 3]], [4, [1], 5], [6], 1, [[2]]]
print sorted(compiler.ast.flatten(a))
# [1, 1, 1, 1, 2, 2, 3, 3, 4, 5, 6, 6, 9]

In python 2.x, you could use the flatten method in the compiler.ast module ("Deprecated since version 2.6: The compiler package has been removed in Python 3.") as follows:

from compiler.ast import flatten

l = [1, [3, 6], 9, [2, [1, 3]], [4, [1], 5], [6], 1, [[2]]]
flattened = flatten(l)
sorted_list = sorted(flattened)

In python 3, to flatten an arbitrarily nested list, you can use the following code, as stated here:

def flatten(l):
    result = []
    for element in l:
        if hasattr(element, "__iter__") and not isinstance(element, str):
            result.extend(flatten(element))
        else:
            result.append(element)
    return result

How about using regular expressions?

>>> import re
>>> l = [1, [3, 6], 9, [2, [1, 3]], [4, [1], 5], [6], 1, [[2]]]
>>> l2 = map(int,re.sub('[\[\]\s]','',str(l)).split(','))
>>> l2.sort()
>>> l2
[1, 1, 1, 1, 2, 2, 3, 3, 4, 5, 6, 6, 9]
>>> 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top