0

I have a tuple of tuples like this:

(('int', 3), (('int', 50), (('int', 4), ('int', 99))))

And I want to get a single flattened tuple like this:

(('int', 3), ('int', 50), ('int', 4), ('int', 99))

The nesting of tuples can be arbitrary.
Most of the questions I found here were about arbitrary flattening of lists.

moso11
  • 15
  • 1
  • 5
  • Does this answer your question? [What is the fastest way to flatten arbitrarily nested lists in Python?](https://stackoverflow.com/questions/10823877/what-is-the-fastest-way-to-flatten-arbitrarily-nested-lists-in-python) – Josh Clark May 06 '20 at 19:11
  • Not exactly. But I was able to use this [solution](https://stackoverflow.com/a/10824484/11961946) and make some changes to get the desired solution. – moso11 May 06 '20 at 19:54
  • you can flatten it and later use for-loop to group two element to create back tuples `('int', 3)`. OR get code for flattening and use some `if/else` to check if you have tuple with `(text, numer)` and skip flattening for these elements – furas May 07 '20 at 06:55
  • The same recursive technique applies; just use different detection for the base case. Or re-create the pairs afterwards. – Karl Knechtel Sep 07 '22 at 07:50

1 Answers1

0

Use any method to create flatten list and use if/else to check if you have tuple ("text", integer) and don't flatten this element.

def flatten(data):
    # check if you have tuple ("text", integer)
    if isinstance(data, tuple) and len(data) == 2 and isinstance(data[0], str) and isinstance(data[1], int):
        # returns it as tuple with single element: (("text", integer),)
        result = [data]
        #print(data)
        return tuple(result)

    # flatten other elements
    result = []
    for item in data:
        result += flatten(item)
    return tuple(result)

data = (('int', 3), (('int', 50), (('int', 4), ('int', 99))))
data = flatten( data )
print(data)

Result:

(('int', 3), ('int', 50), ('int', 4), ('int', 99))
furas
  • 134,197
  • 12
  • 106
  • 148