展平复杂的元组列表

时间:2013-11-11 01:00:52

标签: list python-3.x tuples

我有一个元组列表,带有嵌套元组和列表,看起来像下面的列表:

 a= [('Maria', [1, [2, {'teste': (2, 1.0)}]]), 
('Lisa ', [2, [4, {'field': (4, 0.75), 'bola': (4, 0.25)}]]), 
('John ', [4, [5, {'engine': (5, 0.2), 'wheel': (5, 0.4), 'wheels': (5, 0.2)}]]),
 ('Tracy ', [4, [6, {'pizza': (6, 0.16), 'fish': (6, 0.1), 'animals': (6, 0.1)}]])]

我希望这个列表看起来像:

a.modified = ('Maria', 1, 2, {'teste': (2, 1.0)}]]), 
('Lisa ', 2, 4, {'field': (4, 0.75), 'bola': (4, 0.25)}]]), 
('John ', 4, 5, {'engine': (5, 0.2), 'wheel': (5, 0.4), 'wheels': (5, 0.2)}]]), 
('Tracy ', 4, 6, {'pizza': (6, 0.16), 'fish': (6, 0.1), 'animals': (6, 0.1}]])])

我尝试过一步一步地使用:

a2=[item for sublist in a for item in sublist]

a2 = list(itertools.chain.from_iterable(a))

还有:

a2 = list(item for sublist in a for item in sublist)

似乎没什么用。我知道这太基础了,但是如何解决这个问题的任何提示都会非常有用。谢谢!

1 个答案:

答案 0 :(得分:2)

所以看起来你有一个元组列表和类似链表的结构。每当在链表上操作时,你应该考虑递归。

def flatten(items):
    from itertools import chain
    def flatten_link(link):
        if isinstance(link, list):
            yield link[0]
            for item in flatten_link(link[1]):
                yield item
        elif link is not None:
            yield link
    return list(tuple(chain(item[:1], flatten_link(item[1]))) for item in items)

a = [
    ('Maria', [1, [2, {'teste': (2, 1.0)}]]),
    ('Lisa ', [2, [4, {'field': (4, 0.75), 'bola': (4, 0.25)}]]), 
    ('John ', [4, [5, {'engine': (5, 0.2), 'wheel': (5, 0.4), 'wheels': (5, 0.2)}]]),
    ('Tracy', [4, [6, {'pizza': (6, 0.16), 'fish': (6, 0.1), 'animals': (6, 0.1)}]]),
]
print(flatten(a))

哪个收益率:

[
    ('Maria', 1, 2, {'teste': (2, 1.0)}),
    ('Lisa ', 2, 4, {'bola': (4, 0.25), 'field': (4, 0.75)}),
    ('John ', 4, 5, {'engine': (5, 0.2), 'wheel': (5, 0.4), 'wheels': (5, 0.2)}),
    ('Tracy', 4, 6, {'fish': (6, 0.1), 'animals': (6, 0.1), 'pizza': (6, 0.16)})
]