簡體   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