Skip to main content
 首页 » 编程设计

python之如何解压嵌套列表的内部列表

2024年10月01日8cmt

假设我们有一个嵌套列表,如 nested_list = [[1, 2]]我们想解压这个嵌套列表。 它可以通过以下方式轻松完成(尽管这需要 Python 3.5+):

>>> nested_list = [[1, 2]] 
>>> (*nested_list,)[0] 
[1, 2] 

但是,此操作会解压缩外部 列表。 我想去掉内括号,但没有成功。 是否可以进行这样的操作?

这个例子的动机可能不清楚,所以让我介绍一些背景。 在我的实际工作中,外部列表是 <class 'list'> 的扩展,说 <class 'VarList'> . 这VarList由 deap.creator.create() 创建并具有原始 list 的附加属性没有。 如果我打开外包装 VarList , 我无法访问这些属性。

这就是为什么我需要解压内部列表;我要转VarList的 list的东西变成VarList的东西,不是list的东西。

请您参考如下方法:

如果您想保留VarList 的标识和属性,请尝试在赋值的左侧使用切片运算符,如下所示:

class VarList(list): 
    pass 
 
nested_list = VarList([[1,2]]) 
nested_list.some_obscure_attribute = 7 
print(nested_list) 
 
# Task: flatten nested_list while preserving its object identity and, 
# thus, its attributes 
 
nested_list[:] = [item for sublist in nested_list for item in sublist] 
 
print(nested_list) 
print(nested_list.some_obscure_attribute)