Reputation: 5578
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?
Upvotes: 3
Views: 835
Reputation: 1663
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))
Upvotes: 0
Reputation: 150081
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']]
Upvotes: 3
Reputation: 59731
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']]
Upvotes: 1
Reputation: 4687
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']]
Upvotes: 5