return 如何通过列表理解从列表中的嵌套列表中获得一维列表

How return one dimension list by list comprehension from nested list in list

a = [
[1, 2],
[1, 2]
]

print([x for x in [x for x in a]])
[[1, 2], [1, 2]]

但我想看到类似的东西:

[1, 2, 1, 2]

我是怎么做到的?

试试这个。

a = [
[1, 2],
[1, 2]
]

lst = [q for i in a for q in i]
print(lst)

上面的方法并不总是有效,如果列表是这样的,它会给你一个错误。

a = [[1, 2],[1, 2],2]

但是这个总是有效的。

a = [
[1, 2],
[1, 2]
]
lst = []
for i in a:
    if type(i) == list:
        lst.extend(i)
    else:
        lst.append(i)
print(lst)
    a = [
[1, 2],
[1, 2]
]
flatten_list = lambda y:[x for a in y for x in flatten_list(a)] if type(y) is list else [y]

print(flatten_list(a))