gpt4 book ai didi

Python - "Unlist"列表中的嵌套元素

转载 作者:行者123 更新时间:2023-12-01 02:00:06 29 4
gpt4 key购买 nike

有没有快速的方法来理清列表中的元素?例如:鉴于

list = [[1,2,3],[4,2],2,1,3]

我们将有:

list = [1,2,3,4,2,2,1,3]

最佳答案

将任何非列表值转换为列表后,您可以使用列表理解:

l = [[1,2,3],[4,2],2,1,3]
new_l = [i for b in map(lambda x:[x] if not isinstance(x, list) else x, l) for i in b]

输出:

[1, 2, 3, 4, 2, 2, 1, 3]

编辑:对于嵌套级别,您可以使用带有生成器表达式的递归:

def flatten(d):
v = [[i] if not isinstance(i, list) else flatten(i) for i in d]
return [i for b in v for i in b]

打印(展平(l)输出:

[1, 2, 3, 4, 2, 2, 1, 3]

关于Python - "Unlist"列表中的嵌套元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49773008/

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