展平内部列表中的列表

时间:2019-05-21 22:11:19

标签: 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']

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

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

我已经看到了平整整个列表的通用解决方案,例如:

Flattening a shallow list in Python

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

2 个答案:

答案 0 :(得分:1)

我想您的意思是,您不仅想要显示的输出,还希望在示例输出中另外输出两个。操作方法如下:

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']

答案 1 :(得分:0)

如果您知道如何拼合整个列表,并且想知道仅拼合第一个列表,那么您并不是真正在问如何拼合一个列表,而是在询问如何选择列表中的第一个项目。列表,答案是sublist=lol[0],然后将其他问题的答案应用于sublist