繁体   English   中英

嵌套列表和元组-由内而外

[英]Nested lists and tuples - building inside out

假设我有一个包含两个元素元组的列表,这些元素元组由其他嵌套元组,元组列表或字符串组成。

samp = [('coor', [('test', 'correlation'), 
        [('another', [('nest', 'one')]), ('tags', 'list')], ('threshold', 'foo')])]

>>> samp
[('coor',
  [('test', 'correlation'),
   [('another', [('nest', 'one')]), ('tags', 'list')],
   ('threshold', 'foo')])]

我还有一个类Foo ,它只能正确接受一个不包含任何嵌套列表的列表 ,但可以包含其他Foo 列表

class Foo:
    def __init__(self, li):
        self.l = li
    def __repr__(self):
        return 'Foo<{0}>'.format(str(self.l))

我想将嵌套的结构samp转换为一个有效的巨型Foo ,因此在这种情况下,它看起来像

>>> big_foo
Foo<[('coor', 
      Foo<[('test', 'correlation'), 
           Foo<[('another', 
                 Foo<[('nest', 'one')]>), 
                 ('tags', 'list')]>, 
           ('threshold', 'foo')]>
      )]>

我该如何有效地做到这一点?


我的想法

显然,我将必须构建从最深的嵌套列表内到外的Foo对象。 我知道我可以检查元素是元组还是列表

def is_seq(el):
    return isinstance(el, collections.abc.Sequence) and not isinstance(el, str)

并且我可以检查是否有任何可迭代的对象在某个嵌套级别上包含一个递归的列表,例如

def contains_list(it):
    return any(isinstance(el, list) or (isinstance(el, tuple) and contains_list(el))
                for el in it)

我正在努力的是如何有效地构建新结构,因为元组是不可变的。 由于元组的原因,似乎不可能从内到外地递归地构建结构,因此我真的迷失了一种好的方法。 如果有某种抽象或模块可以为我简化此问题,我很乐意接受。


动机

我正在尝试使用pyRserve包装R库,并且需要R中嵌套命名成员列表的可序列化Python表示形式。pyRserve可以序列化的唯一类似内容是TaggedList ,它不支持在构建时嵌套,所以现在剩下这个问题了。

怎么样:

class Foo:
    def __init__(self, li):
        self.l = li
    def __repr__(self):
        return 'Foo<{0}>'.format(str(self.l))


def make_Foo(obj):
    if isinstance(obj, list):
        return Foo([make_Foo(item) for item in obj])
    elif isinstance(obj, tuple):
        return tuple(make_Foo(item) for item in obj)
    elif isinstance(obj, str):
        return obj
    else:
        raise Exception("Not implemented for type {}".format(type(obj)))

samp = [('coor', [('test', 'correlation'), 
        [('another', [('nest', 'one')]), ('tags', 'list')], ('threshold', 'foo')])]

x = make_Foo(samp)
print(x)

输出:

Foo<[('coor', Foo<[('test', 'correlation'), Foo<[('another', Foo<[('nest', 'one')]>), ('tags', 'list')]>, ('threshold', 'foo')]>)]>

如果您添加一些空格...

Foo<[('coor', 
    Foo<[('test', 'correlation'), 
        Foo<[('another', 
            Foo<[('nest', 'one')]>), 
            ('tags', 'list')]>, 
        ('threshold', 'foo')]>
    )]>

与您所需的输出非常相似。

暂无
暂无

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

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