flatten tuple

Duncan Booth duncan at NOSPAMrcp.co.uk
Tue Apr 23 09:01:04 EDT 2002


John Hunter <jdhunter at nitace.bsd.uchicago.edu> wrote in
news:m2adrvnxiv.fsf at mother.paradise.lost: 

> 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') 
> 

Without checkig for infinite recursion, here is one way to do it:
>>> m = {
    'where': ('was', 'somekey'),
    'somekey': 'someval',
    'someval': ('asking', 'really', 'silly', 'questions')
    }
>>> x = ( 'John', 'Hunter', 'where' )
>>> def expand(aList, aDict):
	if isinstance(aList, tuple):
		aList = list(aList)
	result = []
	while aList:
		head = aList.pop(0)
		if aDict.has_key(head):
			head = [aDict[head]]
		if isinstance(head, tuple) or isinstance(head, list):
			aList[:0] = list(head)
		else:
			result.append(head)
	return tuple(result)

>>> print expand(x, m)
('John', 'Hunter', 'was', 'asking', 'really', 'silly', 'questions')
>>> 

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list