flatten tuple

John Hunter jdhunter at nitace.bsd.uchicago.edu
Mon Apr 22 19:06:48 EDT 2002


I have a tuple of strings and a map from strings to either a string or
a tuple of strings

tuple of strings:
 
  x = ( 'John', 'Hunter', 'where' )


map:

  m = {
       'where': ('was', 'here'),
       'somekey': 'someval'
      }


I want to be able to create a new tuple, which is the expanded and
flattened version x, so that if an element of x is a key of m, then
the new list has that value instead of the key value .  In the example
above, the expansion would give

y = ( 'John', 'Hunter',  ('was', 'here') )

and the flattening would give

y = ( 'John', 'Hunter',  'was', 'here' )

The only hitch is that I want to be able to do this recursively, so
I could have for example

m = {
    'where': ('was', 'somekey'),
    'somekey': 'someval',
    'someval': ('asking', 'really', 'silly', 'questions')
    }

and end up with 


y = ( 'John', 'Hunter',  'was',  'asking', 'really', 'silly', 'questions')

I see that I expose myself to the dangers of infinite recursion which
I should need to guard against, but I am willing to put the burden on
the user not to define recursive tuple/map combinations if checking
against recursion is too difficult.

I would like to use tuples rather than lists because I would like
these tuples to be keys in a hash.

Suggestions?

John Hunter




More information about the Python-list mailing list