2024-10-04 13:21:27 发布
网友
我有一个多层typle/list容器。用插入列表的理解来手动拆箱最终数据让我很头疼。在
[[(23,)],[(124,)],[(45,)]]
在这样的简单列表中,什么是取消最终值装箱的正确方法?在
我已经试过google了,但我只看到了boxi/unboxi是什么的解释,但我确信应该有一些短的方法来实现这个,除了插入列表的理解
假设您的所有数据都不可编辑,我们可以使用递归方法:
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]
如果需要,可以将此方法转换为顺序函数:
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
另一个类似的方法类似于下面的代码。在
好吧,我终于找到了这条路。在
# 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 ) #
In [1]: v = [[(23,)],[(124,)],[(45,)]] In [2]: [b[0] for b in [a[0] for a in v]] Out[3]: [23, 124, 45]
假设您的所有数据都不可编辑,我们可以使用递归方法:
如果需要,可以将此方法转换为顺序函数:
^{pr2}$另一个类似的方法类似于下面的代码。在
^{pr2}$好吧,我终于找到了这条路。在
相关问题 更多 >
编程相关推荐