简体   繁体   English

如何解压嵌套列表的内部列表?

[英]How to unpack inner lists of a nested list?

Suppose we have a nested list like nested_list = [[1, 2]] and we want to unpack this nested list.假设我们有一个嵌套列表,如nested_list = [[1, 2]]并且我们想要解压这个嵌套列表。 It can easily be done with the following (although this requires Python 3.5+):可以通过以下方式轻松完成(尽管这需要 Python 3.5+):

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

However, this operation unpacks the outer list.但是,此操作会解压外部列表。 I want to strips off the inner brackets but I haven't succeeded.我想去掉内括号,但我没有成功。 Is it possible to do such kind of operation?有没有可能做这样的操作?

The motivation might be unclear with this example, so let me introduce some background.这个例子的动机可能不清楚,所以让我介绍一些背景。 In my actual work, the outer list is an extension of <class 'list'> , say <class 'VarList'> .在我的实际工作中,外部列表是<class 'list'>的扩展,比如<class 'VarList'> This VarList is created by deap.creator.create() and has additional attributes that the original list doesn't have.这个VarList是由deap.creator.create()创建的,并且具有原始list没有的附加属性。 If I unpack the outer VarList , I lose access to these attributes.如果我解压外部VarList ,我将无法访问这些属性。

This is why I need to unpack the inner list;这就是为什么我需要解压内部列表; I want to turn VarList of list of something into VarList of something, not list of something.我想将VarList listVarList为某物的VarList ,而不是某物的list

If you want to preserve the identity and attributes of your VarList , try using the slicing operator on the left-hand side of the assignment, like so:如果要保留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)

Yes, that's possible with a slice assignment:是的,这可以通过切片分配实现:

>>> nested_list = [[1, 2]]
>>> id(nested_list)
140737100508424
>>> nested_list[:] = nested_list[0]
>>> id(nested_list)
140737100508424

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM