[英]How to do List flattening inside the loop with list comprehension?
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. 这里我有字典列表,我的目标是迭代列表,每当有2个或更多列表可用时,我想合并它们并附加在输出列表中,只要有一个列表,它就需要存储为它作为。
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]
我可以列出特定元素data[0]
扁平化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'}]
]
You could use conditional list comprehension with itertools.chain
for those elements which need flattening: 您可以对itertools.chain
使用条件列表理解来处理那些需要展平的元素:
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'}]]
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'}]]
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.