How to flatten a tuple in python

前端 未结 6 1552
挽巷
挽巷 2020-11-30 13:42

I have the following element of a list, and the list is 100 elements long.

[(50, (2.7387451803816479e-13, 219))]

How do I convert each elem

6条回答
  •  孤独总比滥情好
    2020-11-30 14:18

    An improvement from @sagacity answer, this will rerun a generator that flattens the tuple using a recursive and yield.

    def flatten_tuple(inp):
        for inp2 in inp:
            if not isinstance(inp2,tuple):
                yield inp2
            elif len(inp2) == 0:
                continue
            else:
                yield from flatten_tuple(inp2)
    

    To make it into list or tuple, use list() or tuple().

    list(flatten_tuple(nested_tuple))
    tuple(flatten_tuple(nested_tuple))
    

提交回复
热议问题