Conversion from tuple to argument list?
mmillikan at vfa.com
mmillikan at vfa.com
Thu Nov 22 13:08:59 EST 2001
mmillikan at vfa.com writes:
<snip>
> However, it doesn't work when the sequence to be unpacked is in any other
> position in the parameter list:
>
> >>> zip(*seqseq,seq)
> File "<stdin>", line 1
> zip(*seqseq,seq)
> ^
> SyntaxError: invalid syntax
>
> Could this syntax be extended to allow the splicing to happen at any
> position within the parameter list?
>
> In the interim, the following module allows the construction:
>
> >>> zip(*splice(unnest(seqseq),seq))
> [(1, 'a', 'x'), (2, 'b', 'y'), (3, 'c', 'z')]
>
> More elaborate splicing also appears to work:
>
> >>> splice([10,20,30],[],unnest(['sam',unnest(unnest(['barney','fred']))]),seq,())
> [[10, 20, 30], [], 'sam', 'barney', 'fred', ('x', 'y', 'z'), ()]
>
> Only lightly tested, on 2.1.1
>
> Feedback on utility and/or horrible flaws appreciated
>
> ------------------------------------------------------------------
simplified to ...
#splice3.py
from __future__ import nested_scopes
class unnest:
'''A minimal wrapper for any sequence. When passed
as an argument to the <splice> function the elements
of the sequence will be spliced into the list returned
replacing the <unnest> instance.'''
def __init__(self,seq):
if isinstance(seq,self.__class__):
self.seq = seq.seq
else:
for item in seq: break
self.seq = seq
def __getitem__(self,index):
return self.seq[index]
def __len__(self):
return len(self.seq)
def splice(*args):
'''Returns a list of its args with any instances
of <unnest> replaced by the items of the unnests
sequence attribute.'''
def _splice(flat,*args):
for arg in args:
if isinstance(arg,unnest):
_splice(flat,*arg.seq)
else:
flat.append(arg)
return flat
return _splice([],*args)
More information about the Python-list
mailing list