3

I know there are many posts on how I can flatten a two-dimensional list but this one is a bit different because it's a mix of two dimensional and three-dimensional list :

items = [[255, 204, 204], ..., [255, 179, 179], [[250, 250, 250], ..., [220, 220, 220]]] 

I'd like this list to be two dimentional only :

items = [[255, 204, 204], ..., [255, 179, 179], [250, 250, 250], ..., [220, 220, 220]] 

I tried to use list comprehension but it doesn't flatten the list correctly :

flat_list = [item for items in l for item in items] 

What would be the best way of flattening mixed dimensional array into a two-dimensional one?

0

4 Answers 4

5
old_list = [[255, 204, 204], [255, 179, 179], [['250, 250, 250'], ['220, 220, 220']]] new_list = [] for i in old_list: if isinstance(i[0], list): for j in i: new_list.append(j) else: new_list.append(i) print new_list 

The output is:

[[255, 204, 204], [255, 179, 179], ['250, 250, 250'], ['220, 220, 220']] 
Sign up to request clarification or add additional context in comments.

Comments

3

You can use a recursive function:

def flatten(items): for item in items: if isinstance(item[0], list): yield from flatten(item) else: yield item 

Demo:

>>> items = [[255, 204, 204], [255, 179, 179], [['250, 250, 250'], ['220, 220, 220']]] >>> list(flatten(items)) [[255, 204, 204], [255, 179, 179], ['250, 250, 250'], ['220, 220, 220']] 

Comments

1
from itertools import chain items = [[255, 204, 204], [255, 179, 179], [['250, 250, 250'], ['220, 220, 220']]] flat_list = list(chain.from_iterable(lst if isinstance(lst[0], list) else [lst] for lst in items)) print(flat_list) >>> [[255, 204, 204], [255, 179, 179], ['250, 250, 250'], ['220, 220, 220']] 

Comments

0
def tree2matrix(T): if T == []: return [] elif type(T) is not list: return [[T]] elif type(T[0]) is not list: return [T] else: return tree2matrix(T[0]) + tree2matrix(T[1:]) X = [[255, 204, 204], [255, 179, 179], [['250, 250, 250'], ['220, 220, 220']]] print(tree2matrix(X)) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.