Reputation: 499
here i am having list of dictionaries, my goal is to iterate over list and whenever there is 2 or more list available, i want to merge them and append in a output list, and whenever there is only one list it needs to be stored as it as.
data = [
[[{'font-weight': '1'},{'font-weight': '1'}],[{'font-weight': '2'},{'font-weight': '2'}]],
[{'font-weight': '3'},{'font-weight': '3'},{'font-weight': '3'}],
[[{'font-weight': '1'},{'font-weight': '1'}],[{'font-weight': '2'},{'font-weight': '2'}]],
[{'font-weight': '3'},{'font-weight': '3'}]
]
I can do list flattening for particular element data[0]
print([item for sublist in data[0] for item in sublist])
[{'font-weight': '1'}, {'font-weight': '1'}, {'font-weight': '2'}, {'font-weight': '2'}]
Expected output :
data = [
[{'font-weight': '1'},{'font-weight': '1'},{'font-weight': '2'},{'font-weight': '2'}],
[{'font-weight': '3'},{'font-weight': '3'},{'font-weight': '3'}],
[{'font-weight': '1'},{'font-weight': '1'},{'font-weight': '2'},{'font-weight': '2'}]
[{'font-weight': '3'},{'font-weight': '3'}]
]
Upvotes: 2
Views: 115
Reputation: 27466
iterate through list and check if each item is lists of list. If so flatten it.
data = [
[[{'font-weight': '1'},{'font-weight': '1'}],[{'font-weight': '2'},{'font-weight': '2'}]],
[{'font-weight': '3'},{'font-weight': '3'},{'font-weight': '3'}],
[[{'font-weight': '1'},{'font-weight': '1'}],[{'font-weight': '2'},{'font-weight': '2'}]],
[{'font-weight': '3'},{'font-weight': '3'}]
]
for n, each_item in enumerate(data):
if any(isinstance(el, list) for el in each_item):
data[n] = sum(each_item, [])
print data
Upvotes: 0
Reputation: 16081
Try this,
result = []
for item in data:
result.append([i for j in item for i in j])
Single line code with list comprehension,
[[i for j in item for i in j] for item in data]
Alternative method,
import numpy as np
[list(np.array(i).flat) for i in data]
Result
[[{'font-weight': '1'},
{'font-weight': '1'},
{'font-weight': '2'},
{'font-weight': '2'}],
[{'font-weight': '3'}, {'font-weight': '3'}, {'font-weight': '3'}],
[{'font-weight': '1'},
{'font-weight': '1'},
{'font-weight': '2'},
{'font-weight': '2'}],
[{'font-weight': '3'}, {'font-weight': '3'}]]
Upvotes: 3
Reputation: 76297
You could use conditional list comprehension with itertools.chain
for those elements which need flattening:
In [54]: import itertools
In [55]: [list(itertools.chain(*l)) if isinstance(l[0], list) else l for l in data]
Out[55]:
[[{'font-weight': '1'},
{'font-weight': '1'},
{'font-weight': '2'},
{'font-weight': '2'}],
[{'font-weight': '3'}, {'font-weight': '3'}, {'font-weight': '3'}],
[{'font-weight': '1'},
{'font-weight': '1'},
{'font-weight': '2'},
{'font-weight': '2'}],
[{'font-weight': '3'}, {'font-weight': '3'}]]
Upvotes: 5