每个列表中包含一个元素的列表列表将变为非列表的项目列表



我有一个列表的列表,每个列表有一个元素。有没有"python"?如何将其转换为元素列表,而不是使用下面显示的循环之外的列表?

un_list = []
for x in home_times:
y=x[0]
un_list.append(y)

可以这样使用列表推导式:

sample_input = [[1], [2], [3]]  # list of lists having one element
output = [i[0] for i in sample_input]

这是output

[1, 2, 3]

在这里阅读更多关于列表推导式的内容。

另一种方法,使用sum函数

lst=[['5'], [3],['7'],['B'],[4]]
output= sum(lst, [])
print(output)

:

['5', 3, '7', 'B', 4]

最新更新