Python converting a tuple (s) of unknown length to a list of strings

I have a recursive string tuple that looks like this:

('text', ('othertext', ('moretext', ('yetmoretext')))) 

(this is actually a tuple of string tuples - it is built recursively)

And I would like to smooth it into a list of lines, as a result of which foo [1] will contain "text", foo [2] "other text", etc.

How to do this in Python?

The duplicate is a 2D list of lists, but here I am dealing with a recursive tuple.

+6
source share
3 answers

I myself found the answer, I will provide it here for future reference:

 stringvar = [] while type(tuplevar) is tuple: stringvar.append(tuplevar[0]) tuplevar=tuplevar[1] stringvar.append(tuplevar) # to get the last element. 

It may not be the cleanest / shortest / most elegant solution, but it works and it seems pretty "Pythonic".

+3
source

If you are happy that the recursion level will not become terrible (and you are using an updated version of Python):

 def unpack(obj): for x in obj: if isinstance(x, str): yield x elif isinstance(x, tuple): yield from unpack(x) else: raise TypeError x = ('text', ('othertext', ('moretext', ('yetmoretext',)))) result = list(unpack(x)) print(result) 

You'll get:

 ['text', 'othertext', 'moretext', 'yetmoretext'] 

This will also work if there is more than 1 row before the next tuple, or if there are tuples directly in the tuples or rows after the tuples, etc. You can also easily change it to work with other types, if you need, I probably was too wrong on the side of caution.

+1
source

This is how I approach him. This is very similar to the previous answer, but it is more general in the application, since it allows you to smooth any type of iteration, except for string objects (i.e. Lists and tuples), and also allows you to smooth lists of non-string objects.

 # Python 3. from collections import abc def flatten(obj): for o in obj: # Flatten any iterable class except for strings. if isinstance(o, abc.Iterable) and not isinstance(o, str): yield from flatten(o) else: yield o data = ('a', ('b', 'c'), [1, 2, (3, 4.0)], 'd') result = list(flatten(data)) assert result == ['a', 'b', 'c', 1, 2, 3, 4.0, 'd'] 
+1
source

Source: https://habr.com/ru/post/987063/


All Articles