How to flatten a list of nested tuples in Python?

前端 未结 3 555
自闭症患者
自闭症患者 2020-12-10 19:39

I have a list of tuples that looks like this:

[(\'a\', \'b\'), (\'c\', \'d\'), ((\'e\', \'f\'), (\'h\', \'i\'))]

I want to turn it into thi

3条回答
  •  粉色の甜心
    2020-12-10 20:17

    A one-line solution would be using itertools.chain:

    >>> l = [('a', 'b'), ('c', 'd'), (('e', 'f'), ('h', 'i'))]
    >>> from itertools import chain
    >>> [*chain.from_iterable(x if isinstance(x[0], tuple) else [x] for x in l)]
    [('a', 'b'), ('c', 'd'), ('e', 'f'), ('h', 'i')]
    

提交回复
热议问题