gpt4 book ai didi

python - 如何使用列表理解在循环内进行列表展平?

转载 作者:行者123 更新时间:2023-11-28 20:17:39 25 4
gpt4 key购买 nike

这里我有字典列表,我的目标是遍历列表,只要有 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'}]
]

最佳答案

你可以使用 conditional list comprehensionitertools.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'}]]

关于python - 如何使用列表理解在循环内进行列表展平?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39385026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com