這裏我有詞典列表,我的目標是遍歷列表,每當有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謝謝!我也喜歡你的回答。 –