how to join array of integers?
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Sat Sep 15 19:54:58 EDT 2007
On Sat, 15 Sep 2007 15:56:40 +0200, Arnau Sanchez wrote:
> js escribió:
>
>>> On 9/15/07, Summercool <Summercoolness at gmail.com> wrote:
>
>>> in Python... is the method to use ",".join() ? but then it must take
>>> a list of strings... not integers...
>>>
>>> any fast method?
>
> > print ''.join([str(i) for i in [1,2,3]])
>
> It's better to use generator comprehension instead of LC:
>
> ",".join(str(i) for i in [1, 2, 3])
Really? Why do you say that a generator expression is "better" than a
list comprehension?
>>> import timeit
>>> timeit.Timer("', '.join([str(i) for i in [1,2,3]])", "").repeat()
[5.0969390869140625, 4.5353701114654541, 4.5807528495788574]
>>> timeit.Timer("', '.join(str(i) for i in [1,2,3])", "").repeat()
[11.651727914810181, 10.635221004486084, 10.522483110427856]
The generator expression takes about twice as long to run, and in my
opinion it is no more readable. So what's the advantage?
> Or, if you happen to like the itertools modules:
>
> from itertools import imap
> ",".join(imap(str, [1, 2, 3]))
>>> timeit.Timer("', '.join(imap(str, [1,2,3]))",
... "from itertools import imap").repeat()
[9.3077328205108643, 8.655829906463623, 8.5271010398864746]
Faster than a generator expression, but still pretty slow.
--
Steven.
More information about the Python-list
mailing list