Is there a Python module that already does this?
Brian Kelley
bkelley at wi.mit.edu
Wed Feb 6 10:31:11 EST 2002
MDK wrote:
>I need to convert a list into a list of characters.
>
>For example:
>
>("cat",5,['dog',[3,3,1]],"zoo")
>
>Would become:
>
>('c','a','t',5,'d','o','g',3,3,1,'z','o','o')
>
>Any information would be appreciated.
>
>Thanks
>
>
It's an interesting problem. A particularly slow solution follows.
Interestingly, it purposely uses the maximum recursion error to keep
the code simpler and not have to do any type checking. Given this fact,
it's faster than I expected :)
def _delve(s, target):
"""(s, target)->recursively split elements of s and
append each element to the target list
Warning, purposely uses maximum recursions
for simplicity!"""
try:
for data in s:
_delve(data, target)
except TypeError:
target.append(s)
except RuntimeError:
# catch maximum recursion errors
# this occurs when trying to split a character
# string like "s"
target.append(s)
def delve(input):
"""(input)->recursively split input
i.e.
('cat', 5, ['dog', [3, 3, 1]], 'zoo')
will reult in
('c', 'a', 't', 5, 'd', 'o', 'g', 3, 3, 1, 'z', 'o', 'o')
warning, purposely uses maximum recursions!
"""
target = []
_delve(data, target)
return tuple(target)
print delve(("cat",5,['dog',[3,3,1]],"zoo"))
Brian Kelley
Whitehead Institute for Biomedical Research
More information about the Python-list
mailing list