这里我有词典列表,我的目标是遍历列表,每当有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'}]
]
完美!像老板@Ami,谢谢 –
我更喜欢这个答案Nice work, –
@Rahul谢谢!我也喜欢你的回答。 –