convert tuple to string
Alex Martelli
aleax at aleax.it
Mon Aug 11 16:40:13 EDT 2003
Anand Pillai wrote:
> Assuming 't' is your tuple of values,
>
> print reduce(lambda x, y: x + ',' + y, map(lambda x: x[0], t))
>
> will print a string with all first elements of the tuple
> (your strings), separated by a comma.
So will ','.join([ x[0] for x in t ]) .
So, let's look at performance. The complex, lambda-rich
expression with a map and a reduce...:
python2.3 timeit.py -s't=tuple([ (str(x),) for x in range(30) ])'
'reduce(lambda x,y:x+","+y, map(lambda x:x[0],t))'
10000 loops, best of 3: 59.3 usec per loop
The simple expression based on a list comprehension:
python2.3 timeit.py -s't=tuple([ (str(x),) for x in range(30) ])'
'",".join([ x[0] for x in t ])'
10000 loops, best of 3: 24.4 usec per loop
I think this is great fodder for the underground movement aiming
to remove lambda, map and reduce. All that complication just
to slow things down by two times and a half...?-!
Alex
More information about the Python-list
mailing list