gpt4 book ai didi

python - 展平列表列表中的内部列表

转载 作者:行者123 更新时间:2023-11-28 17:59:45 26 4
gpt4 key购买 nike

假设我有以下对象列表:

lol = [['When was America discovered by Christopher Colombus?', ['1492', '1510', '1776', '1820'], '1492'], ['What is the name of the school that Harry Potter attends?', ['Hogwarts', 'Gryffindor', 'Voldemort', 'Magic School'], 'Hogwarts'], ['How many colors are there in the common depiction of the rainbow?', ['5', '7', '9', '11'], '7']

我正在尝试展平内部列表(例如删除括号)。结果看起来像

['When was America discovered by Christopher Colombus?', '1492', '1510', '1776', '1820', '1492']

我已经看到了扁平化整个列表的通用解决方案,如下所示:

Flattening a shallow list in Python

但我不知道如何在更大的列表列表中有选择地展平单个列表。

最佳答案

我认为您的意思是您不仅想要显示的输出,还想要样本输出中的其他两个输出。以下是如何做到这一点:

lol = [['When was America discovered by Christopher Colombus?', ['1492', '1510', '1776', '1820'], '1492'], ['What is the name of the school that Harry Potter attends?', ['Hogwarts', 'Gryffindor', 'Voldemort', 'Magic School'], 'Hogwarts'], ['How many colors are there in the common depiction of the rainbow?', ['5', '7', '9', '11'], '7']]

r = []
for x in lol:
r.append([x[0]] + x[1] + [x[2]])

for rr in r:
print(rr)

结果:

['When was America discovered by Christopher Colombus?', '1492', '1510', '1776', '1820', '1492']
['What is the name of the school that Harry Potter attends?', 'Hogwarts', 'Gryffindor', 'Voldemort', 'Magic School', 'Hogwarts']
['How many colors are there in the common depiction of the rainbow?', '5', '7', '9', '11', '7']

关于python - 展平列表列表中的内部列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56246950/

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