Python Forum
Flattening List - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Flattening List (/thread-7806.html)



Flattening List - mp3909 - Jan-25-2018

Just a curious question, how would one flatten the following list [[[2], [4, 1, 3]], [5, 7], 1, 10, [[[5, 5, 5], [4, 4, 4]]]] ?


RE: Flattening List - league55 - Jan-25-2018

I think with zip().


RE: Flattening List - Gribouillis - Jan-25-2018

Here is a recursive solution
from itertools import chain

def iflatten(seq):
    return chain.from_iterable(
        iflatten(x) if isinstance(x, list) else (x,) for x in seq)

def flatten(seq):
    return list(iflatten(seq))

if __name__ == '__main__':
    L = [[[2], [4, 1, 3]], [5, 7], 1, 10, [[[5, 5, 5], [4, 4, 4]]]]
    print(flatten(L))
Output:
[2, 4, 1, 3, 5, 7, 1, 10, 5, 5, 5, 4, 4, 4]



RE: Flattening List - ka06059 - Jan-25-2018

def flatten(list):
	flatted = []
	for element in list:
		if type(element) != type([]):
			flatted+=[element]
		else:
			flatted+=flatten(element)
	return flatted
A = [[[2], [4, 1, 3]], [5, 7], 1, 10, [[[5, 5, 5], [4, 4, 4]]]]
flatten(A)
codes with basic keywords and list operation only


RE: Flattening List - Mekire - Jan-25-2018

Black magic:
>>> a = [[[2], [4, 1, 3]], [5, 7], 1, 10, [[[5, 5, 5], [4, 4, 4]]]]
>>> b = eval(repr(a).replace("[","").replace("]",""))
>>> b
(2, 4, 1, 3, 5, 7, 1, 10, 5, 5, 5, 4, 4, 4)
>>>
But, in all seriousness, don't do that.

eval is bad, you say? I know:
>>> a = [[[2], [4, 1, 3]], [5, 7], 1, 10, [[[5, 5, 5], [4, 4, 4]]]]
>>> b = list(map(int, repr(a).replace("[","").replace("]","").split(",")))
>>> b
[2, 4, 1, 3, 5, 7, 1, 10, 5, 5, 5, 4, 4, 4]
>>>
Don't do this either.


RE: Flattening List - Gribouillis - Jan-25-2018

(Jan-25-2018, 11:14 PM)Mekire Wrote: Black magic:
There will be some trouble if the list contains literal strings instead of integers!


RE: Flattening List - Mekire - Jan-25-2018

(Jan-25-2018, 11:18 PM)Gribouillis Wrote:
(Jan-25-2018, 11:14 PM)Mekire Wrote: Black magic:
There will be some trouble if the list contains literal strings instead of integers!
The dark arts can be cruel and unforgiving.


RE: Flattening List - league55 - Jan-26-2018

Teaching the Qliphoth is forbidden, my friends.


RE: Flattening List - snippsat - Jan-26-2018

I want to break Python 2 support Evil bye using yield from.
def flatten(seq):
    for item in seq:
        if isinstance(item, list):
            yield from flatten(item)
        else:
            yield item

lst = [[[2], [4, 1, 3]], [5, 7], 1, 10, [[[5, 5, 5], [4, 4, 4]]]]
print(list(flatten(lst)))
Output:
[2, 4, 1, 3, 5, 7, 1, 10, 5, 5, 5, 4, 4, 4]