这里我有字典列表,我的目标是迭代列表,每当有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'}]
]
我可以为特定元素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'}]
预期产出:
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'}]
]
答案 0 :(得分:5)
您可以将conditional list comprehension与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'}]]
答案 1 :(得分:3)
试试这个,
result = []
for item in data:
result.append([i for j in item for i in j])
包含列表理解的单行代码,
[[i for j in item for i in j] for item in data]
替代方法,
import numpy as np
[list(np.array(i).flat) for i in 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'}]]
答案 2 :(得分:0)
遍历列表并检查每个项目是否为列表列表。如果这样压平它。
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