-1

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

 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)

似乎没有任何效果。我知道这太基本了,但是任何关于如何解决这个问题的提示都会很有帮助。谢谢!

4

1 回答 1

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)})
]
于 2013-11-11T01:42:29.160 回答