flatten tuple
Bengt Richter
bokr at oz.net
Tue Apr 23 16:24:36 EDT 2002
On Mon, 22 Apr 2002 18:06:48 -0500, John Hunter <jdhunter at nitace.bsd.uchicago.edu> wrote:
>
>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')
> }
>
Depending on your space/time tradeoffs, and when/how you build m
(i.e., is it built once and then used unchanged?) seems like you
could keep m flat, or flatten it once (assuming no cycles). E.g.,
m = {
'where': ('was', 'asking', 'really', 'silly', 'questions'),
'somekey': ('asking', 'really', 'silly', 'questions'),
'someval': ('asking', 'really', 'silly', 'questions')
}
(Where somekey and someval might even be eliminated if they can't
appear in x tuples)
then
x = ( 'John', 'Hunter', 'where' )
could become
y = ( 'John', 'Hunter', 'was', 'asking', 'really', 'silly', 'questions')
in one non-recursive lookup for each word, e.g.,
>>> def sub(t):
... result=[]
... for w in t:
... result.extend(m.get(w,[w]))
... return tuple(result)
...
>>> x
('John', 'Hunter', 'where')
>>> y = sub(x)
>>> y
('John', 'Hunter', 'was', 'asking', 'really', 'silly', 'questions')
Note that all the m[k] values have to be tuples and x[i] have to be strings
for this example.
>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.
>
It's hard to suggest useful stuff without the big picture.
Regards,
Bengt Richter
More information about the Python-list
mailing list