How to flatten a tuple in python

前端 未结 6 1556
挽巷
挽巷 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:06

    Your could use the following function and apply it in a loop to every element in the list.

    import type
    
    def flatten(T):
        if type(T) != types.TupleType: return (T,)
        elif len(T) == 0: return ()
        else: return flatten(T[0]) + flatten(T[1:])
    

    How it works:

    • First it will be checked if type is tuple, if not, it "tuples" the argument
    • Second line returns an empty tuple, if tuple is empty
    • Third line gets out the first element and calls the function recursively

    The nice thing in this solution is:

    • It is not necessary to know the structure of the given tuple
    • The tuple can be nested arbitrarily deep
    • Works in Python 2.7

    The code is slightly adapted from following source:
    https://mail.python.org/pipermail/tutor/2001-April/005025.html

    Hope it helps someone :)

提交回复
热议问题