正确的方法来取消打开多层值

时间:2014-03-20 13:20:32

标签: python

我有一个多层的typle / list容器。使用插入的列表推导手动拆箱最终数据给我带来了很多麻烦。

[[(23,)],[(124,)],[(45,)]]

在这样的简单列表中打开最终值的正确方法是什么?

[23,124,45]

我已经尝试过google了,但是我只看到了对boxi / unboxing的解释,但我确定应该有一些简短的方法来做到这一点,除了插入列表推导

3 个答案:

答案 0 :(得分:0)

In [1]: v = [[(23,)],[(124,)],[(45,)]]

In [2]: [b[0] for b in [a[0] for a in v]]
Out[3]: [23, 124, 45]

答案 1 :(得分:0)

srcList = [[(23,)],[(124,)],[(45,)]]
dstList = []
#--------------------------------------------------------------------
def Expand( srcList ) :
    if hasattr(srcList, '__iter__'):
        for i in srcList:
            Expand( i )
    else:
        dstList.append( srcList )
#--------------------------------------------------------------------
if __name__ == '__main__':
    Expand( srcList )
    print dstList

另一种类似的方法喜欢以下代码。

#--------------------------------------------------------------------
class   Expander:
    def __init__( self ):
        self.resultList = []

    def Expand( self, srcList ):
        self.resultList = []
        self.Internal_Expand( srcList )
        return self.resultList

    def Internal_Expand( self, srcList ):
        if hasattr(srcList, '__iter__'):
            for i in srcList:
                self.Internal_Expand( i )
        else:
            self.resultList.append( srcList )
#--------------------------------------------------------------------
if __name__ == '__main__':
    srcList = [[(23,)],[(124,)],[(45,)]]
    print Expander().Expand( srcList )
#--------------------------------------------------------------------
好的,最后我找到了这种方式。

#--------------------------------------------------------------------
def Expand( srcList ):
    resultList = []
    def Internal_Expand( xList ):
        if hasattr(xList, '__iter__'):
            for i in xList:
                Internal_Expand( i )
        else:
            resultList.append( xList )
    Internal_Expand( srcList )
    return resultList
#--------------------------------------------------------------------
if __name__ == '__main__':
    srcList = [[(23,)],[(124,)],[(45,)]]
    print Expand( srcList )
#--------------------------------------------------------------------

答案 2 :(得分:0)

假设您的所有数据都不是可迭代的,我们可以使用递归方法:

import collections

def iterable(obj):
    return isinstance(obj, collections.Iterable)

def unbox(obj):
    if iterable(obj):
        result = []
        for x in obj:
            result.extend(unbox(x))
        return result
    else:
        return [obj]

如果需要,可以将此方法转换为顺序函数:

from collections import deque

def unbox(obj):
    obj_list = deque([obj])
    result = []
    while(len(obj_list) > 0):
        current = obj_list.popleft()
        if iterable(current):
            obj_list.extend(current)
        else:
            result.append(current)
    return result