如何在python列表中合并不同的值类型?



假设我有三个列表:


data = [
{"type": "special", "prize": "32220402"},
{"type": "grand", "prize": "99194290"},
[
{"type": "first", "prize": "16525386"},
{"type": "first", "prize": "28467179"},
{"type": "first", "prize": "27854976"},
],
[
{"type": "second", "prize": "6525386"},
{"type": "second", "prize": "8467179"},
{"type": "second", "prize": "7854976"},
],
]

如何将上述列表中的所有值组合为:

[
{"type": "special", "prize": "32220402"},
{"type": "grand", "prize": "99194290"},
{"type": "first", "prize": "16525386"},
{"type": "first", "prize": "28467179"},
{"type": "first", "prize": "27854976"},
{"type": "second", "prize": "6525386"},
{"type": "second", "prize": "8467179"},
{"type": "second", "prize": "7854976"},
]

完成此任务的语法最干净的方法是什么?

谢谢你的帮助!

这是一个可能的解决方案:

[data[0], data[1], *data[2], *data[3]]

如果您喜欢更通用的方法:

[dct for x in data for dct in (x if isinstance(x, list) else (x,))]

如果有较大的数字,则可以使用循环:

result = []
for i in data:
if isinstance(i, list):
for j in i:
result.append(j)
else:
result.append(i)

看起来您想要扁平化嵌入列表,并保持其余部分不变。应该这样做:

flat = []
for e in data:
if isinstance(e, list):
flat.extend(e)
else:
flat.append(e)

相关内容

  • 没有找到相关文章

最新更新