473,836 Members | 1,572 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to join array of integers?

i think in Ruby, if you have an array (or list) of integers

foo = [1, 2, 3]

you can use foo.join(",") to join them into a string "1,2,3"

in Python... is the method to use ",".join() ? but then it must take
a list of strings... not integers...

any fast method?

Sep 15 '07
23 19757
Grant Edwards ha escrito:
Or, if you happen to like the itertools modules:

from itertools import imap
",".join(imap(s tr, [1, 2, 3]))

It's nice people have invented so many ways to spell the
builting "map" ;)
Did you wonder why the Python developers bother to implement "imap" if
"map" was already there?
>",".join(map(s tr,[1,2,3]))
'1,2,3'
Of course the result is the same, but "map" returns a list while
"itertools.imap " returns an iterator. Fortunately, "map" will become
lazy on Py3000:

http://mail.python.org/pipermail/pyt...st/009207.html

As you said, it won't be noticeable for short lists, but it's a good
programming practice to use generators instead of lists (if you don't
really need a list!)

arnau

Sep 15 '07 #11
Grant Edwards wrote:
On 2007-09-15, Erik Jones <er**@myemma.co mwrote:
>>>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])
Why is that? That entire expression must be evaluated to obtain the
result, so what is the advantage of using a generator comprehension
v. a list comprehension?

The generator avoids creating the intermediate list -- it
generates the intermediate values on the fly. For short
sequences it probably doesn't matter much. For a very long
list it's probably noticable.
Not true. str.join() creates a list from the iterator if it is not already a
list or a tuple. In Objects/stringobject.c, look at string_join(); it calls
PySequence_Fast () on the argument. Looking in Objects/abstract.c, we see that
PySequence_Fast () short-circuits lists and tuples but builds a full list from
the iterable otherwise.

map() seems to reliably be the fastest option, and list comprehensions seem to
slightly edge out generator comprehensions if you do the timings.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco

Sep 15 '07 #12
On 2007-09-15, Robert Kern <ro*********@gm ail.comwrote:
Grant Edwards wrote:
>On 2007-09-15, Erik Jones <er**@myemma.co mwrote:
>>>>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])
Why is that? That entire expression must be evaluated to
obtain the result, so what is the advantage of using a
generator comprehension v. a list comprehension?

The generator avoids creating the intermediate list -- it
generates the intermediate values on the fly. For short
sequences it probably doesn't matter much. For a very long
list it's probably noticable.

Not true. str.join() creates a list from the iterator if it is
not already a list or a tuple.
So the iterator avoids creating an intermediate list, but the
join method goes ahead and does it anyway?
In Objects/stringobject.c, look at string_join(); it calls
PySequence_Fast () on the argument. Looking in
Objects/abstract.c, we see that PySequence_Fast ()
short-circuits lists and tuples but builds a full list from
the iterable otherwise.
So what's the point of iterables if code is going to do stuff
like that when it wants to iterate over a sequence?
map() seems to reliably be the fastest option,
Which is apparently going away in favor of the slower iterator
approach?
and list comprehensions seem to slightly edge out generator
comprehensions if you do the timings.
--
Grant Edwards grante Yow! Clear the
at laundromat!! This
visi.com whirl-o-matic just had a
nuclear meltdown!!
Sep 15 '07 #13
On Sat, 15 Sep 2007 15:56:40 +0200, Arnau Sanchez wrote:
js escribió:
>>On 9/15/07, Summercool <Su************ @gmail.comwrote :
>>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(st r(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.0969390869140 625, 4.5353701114654 541, 4.5807528495788 574]
>>timeit.Timer( "', '.join(str(i) for i in [1,2,3])", "").repeat( )
[11.651727914810 181, 10.635221004486 084, 10.522483110427 856]

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(s tr, [1, 2, 3]))
>>timeit.Timer( "', '.join(imap(str , [1,2,3]))",
.... "from itertools import imap").repeat()
[9.3077328205108 643, 8.6558299064636 23, 8.5271010398864 746]

Faster than a generator expression, but still pretty slow.

--
Steven.
Sep 15 '07 #14
On Sat, 15 Sep 2007 16:07:07 +0000, Grant Edwards wrote:

It's nice people have invented so many ways to spell the builting "map"
;)
>>>",".join(map (str,[1,2,3]))
'1,2,3'

The oldest solution, and if not the fastest, at least neck-and-neck with
the list comprehension.
>>timeit.Timer( "', '.join(map(str, [1,2,3]))", "").repeat( )
[5.0320308208465 576, 4.1513419151306 152, 4.0970909595489 502]
For those who missed my earlier post:

list comp, best of three for one million iterations: 4.53 seconds
generator expression: 10.52 seconds
itertools.imap: 8.52 seconds

Your mileage may vary.

I think it is a crying shame that Guido's prejudice against functional
programming seems to have increased over the years, instead of decreased.
Iterators are wonderful tools, but professional tradesmen use more than
one sort of hammer. (There are claw hammers and ball peen hammers and
tack hammers and wooden mallets and...)

"One obvious way to do it" should not mean "force everyone to use a tack
hammer to drive in nails, because it's the only hammer in the tool box".
It should mean "it's obvious, use the tack hammer to drive in tacks and
the claw hammer for carpentry and the wooden mallet for beating out dints
in sheet metal and..."
--
Steven.
Sep 16 '07 #15
Grant Edwards wrote:
On 2007-09-15, Robert Kern <ro*********@gm ail.comwrote:
>Grant Edwards wrote:
>>On 2007-09-15, Erik Jones <er**@myemma.co mwrote:

>print ''.join([str(i) for i in [1,2,3]])
It's better to use generator comprehension instead of LC:
>
",".join(st r(i) for i in [1, 2, 3])
Why is that? That entire expression must be evaluated to
obtain the result, so what is the advantage of using a
generator comprehension v. a list comprehension?
The generator avoids creating the intermediate list -- it
generates the intermediate values on the fly. For short
sequences it probably doesn't matter much. For a very long
list it's probably noticable.
Not true. str.join() creates a list from the iterator if it is
not already a list or a tuple.

So the iterator avoids creating an intermediate list, but the
join method goes ahead and does it anyway?
Yup.
>In Objects/stringobject.c, look at string_join(); it calls
PySequence_Fas t() on the argument. Looking in
Objects/abstract.c, we see that PySequence_Fast ()
short-circuits lists and tuples but builds a full list from
the iterable otherwise.

So what's the point of iterables if code is going to do stuff
like that when it wants to iterate over a sequence?
Some code dealing with sequences can be recast in terms of iterators of unknown
length. Some can't. Some are better cast in terms of iterators than sequences;
some aren't.
>map() seems to reliably be the fastest option,

Which is apparently going away in favor of the slower iterator
approach?
It's only slower in this case. Of course, the main difference is where the loop
takes place, in C or in Python. imap() appears to give the same performance as
map().

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco

Sep 16 '07 #16
Steven D'Aprano <st***@REMOVE-THIS-cybersource.com .auwrites:
On Sat, 15 Sep 2007 15:56:40 +0200, Arnau Sanchez wrote:
>js escribió:
>>>On 9/15/07, Summercool <Su************ @gmail.comwrote :
>>>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.0969390869140 625, 4.5353701114654 541, 4.5807528495788 574]
>>>timeit.Timer ("', '.join(str(i) for i in [1,2,3])", "").repeat( )
[11.651727914810 181, 10.635221004486 084, 10.522483110427 856]

The generator expression takes about twice as long to run, and in my
opinion it is no more readable. So what's the advantage?
If you do it with a decent size list they take more or less the same
time. You'd presumably expect the generator to use less memory; which
might be an advantage if you have large lists.

Isn't it odd that the generator isn't faster, since the comprehension
presumably builds a list first and then iterates over it, whereas the
generator doesn't need to make a list?
Sep 16 '07 #17
Paul Rudin <pa*********@ru din.co.ukwrote:
...
Isn't it odd that the generator isn't faster, since the comprehension
presumably builds a list first and then iterates over it, whereas the
generator doesn't need to make a list?
The generator doesn't, but the implementation of join then does
(almost). See Objects/stringobject.c line 1745:

seq = PySequence_Fast (orig, "");

As per <http://docs.python.org/api/sequence.html>,
"""
PyObject* PySequence_Fast (PyObject *o, const char *m)

Return value: New reference.

Returns the sequence o as a tuple, unless it is already a tuple or list,
in which case o is returned. Use PySequence_Fast _GET_ITEM() to access
the members of the result. Returns NULL on failure. If the object is not
a sequence, raises TypeError with m as the message text.
"""

If orig is neither a list nor a tuple, but for example a generator,
PySequence_Fast builds a list from it (even though its docs which I just
quoted says it builds a tuple -- building the list is clearly the right
choice, so I'd say it's the docs that are wrong, not the code;-)... so
in this particular case the usual advantage of the generator disappears.

PySequence_fast is called in 13 separate spots in 8 C files in the
Python 2.5 sources, so there may a few more surprises like this;-).
Alex

Sep 16 '07 #18
On Sun, 16 Sep 2007 19:25:22 +0100, Paul Rudin wrote:
>The generator expression takes about twice as long to run, and in my
opinion it is no more readable. So what's the advantage?

If you do it with a decent size list they take more or less the same
time.
Did you try it, or are you guessing? What do you call a decent size?

You'd presumably expect the generator to use less memory; which
might be an advantage if you have large lists.
Unfortunately, Python doesn't make it as easy to measure memory use as it
does to time snippets of code, so that's just a hypothetical.

Isn't it odd that the generator isn't faster, since the comprehension
presumably builds a list first and then iterates over it, whereas the
generator doesn't need to make a list?
Who says it doesn't need to make a list? string.join() needs a sequence.
--
Steven.
Sep 16 '07 #19
On Sep 15, 8:36 am, Summercool <Summercooln... @gmail.comwrote :
i think in Ruby, if you have an array (or list) of integers

foo = [1, 2, 3]

you can use foo.join(",") to join them into a string "1,2,3"

in Python... is the method to use ",".join() ? but then it must take
a list of strings... not integers...

any fast method?
Isn't the OP just looking for something like:
>>foo=[1,2,3]
bar=[4,5,6]
foo+bar
[1, 2, 3, 4, 5, 6]
>>>
Sep 17 '07 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

58
10198
by: jr | last post by:
Sorry for this very dumb question, but I've clearly got a long way to go! Can someone please help me pass an array into a function. Here's a starting point. void TheMainFunc() { // Body of code... TCHAR myArray; DoStuff(myArray);
4
4274
by: William | last post by:
I would appreciate your help on the following programming questions: 1. Given an array of length N containing integers between 1 and N, determine if it contains any duplicates. HINT: The solution is: http://domino.research.ibm.com/Comm/wwwr_ponder.nsf/solutions/January2004.html but I don't understand what they meant by "Let f(x) be the location of the
20
4728
by: Pavel Stehule | last post by:
Hello, Is possible merge two arrays like array + array => array select array_append(array, array); ERROR: function array_append(integer, integer) does not exist
46
3263
by: RoSsIaCrIiLoIA | last post by:
Write a function that gets an array of unsigned int fill it with random values all differents, and sorts it. It should be faster than qsort too. Do you like my solution? _______________________ #include <stdio.h> #include <stdlib.h> #include <time.h>
8
1701
by: engaref | last post by:
Hello Every body, I am new with C programming.I have received the Problems from my advisor on Array but I did not find any Proper answer yet. If Possible,please make a solution for the Problems. Thanks The Problems are as follows: 1-Declare an array of length of 10 and read integers into the elements
14
15055
by: Bob | last post by:
I have a function that takes in a list of IDs (hundreds) as input parameter and needs to pass the data to another step as a comma delimited string. The source can easily create this list of IDs in a comma-delimited string or string array. I don't want it to be a string because I want to overload this function, and it's sister already uses a string input parameter. Now if I define the function to take in a string array, it solves my...
2
1338
by: JP2006 | last post by:
I have a situation where I have 2 tables - NODES and TAGS. Nodes is the main table and contains various columns one of which is tagID. Tags contains a list of tag names and tagIDs. When a user adds an entry to the Nodes table they can specify one or more tags for the entry. Then when the form is posted if there were multiple tags in the post their tagIDs are comma seperated before being inserted in the tagID column of the Nodes table....
7
6445
by: heddy | last post by:
I have an array of objects. When I use Array.Resize<T>(ref Object,int Newsize); and the newsize is smaller then what the array was previously, are the resources allocated to the objects that are now thown out of the array released properly by the CLI?
2
1184
by: André | last post by:
Hi, I have a two-dimension array with integers and i want to join it into a string. See my code: dim va(10,5) as integer dim mystring as string .... for j=1 to 10 for k=1 to 5 mystring = Join(";",va(j,k).ToString)
0
9816
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9668
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10840
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10546
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10254
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9371
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6978
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5647
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5823
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.