473,750 Members | 2,279 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

transforming a list into a string

Let us assume I have a list like

['1','2','7','8' ,'12','13]

and would like to transoform it into the string

'{1,2},{7,8},{1 2,13}'

Which is the simplest way of achiebing this? (The list is in fact much
longer and I may have to cut the resulting strings into chunks of 100 or
so.)

TIA,

jb

Jul 18 '05 #1
34 3292
jblazi wrote:
Let us assume I have a list like

['1','2','7','8' ,'12','13]

and would like to transoform it into the string

'{1,2},{7,8},{1 2,13}'

Which is the simplest way of achiebing this? (The list is in fact much
longer and I may have to cut the resulting strings into chunks of 100 or
so.)

from itertools import izip
items = ['1','2','7','8' ,'12','13']
it = iter(items)
",".join(["{%s,%s}" % i for i in izip(it, it)])

'{1,2},{7,8},{1 2,13}'
Peter

Jul 18 '05 #2
In article <pa************ *************** *@hotmail.com>,
jblazi <jb****@hotmail .com> wrote:
Let us assume I have a list like

['1','2','7','8' ,'12','13]
I'm assuming there's supposed to be another single-quote after the 13?
and would like to transoform it into the string

'{1,2},{7,8},{1 2,13}'
This works, and is pretty straight-forward:

source = ['1','2','7','8' ,'12','13']
temp = []

while source:
x = source.pop(0)
y = source.pop(0)
temp.append ('{%s,%s}' % (x, y))

result = ','.join (temp)
print result

This prints what you want:

$ /tmp/list2string.py
{1,2},{7,8},{12 ,13}

Accumulating the repeating bits of the result string in a list, and then
putting them together with a join operation is a common idiom in python.
You can build up strings by doing string addition:

temp = temp + '{%s,%s}' % (x, y)

This will have the same result, but suffers from quadratic run times as
it keeps building and destroying immutable strings.
Which is the simplest way of achiebing this? (The list is in fact much
longer and I may have to cut the resulting strings into chunks of 100 or
so.)


How long is "much longer", and how important is it that this runs fast?
The code above runs in O(n). You can probably play some tricks to tweak
the speed a little, but in the big picture, you're not going to do any
better than O(n).

The above code also assumes you have an even number of items in source,
and will bomb if you don't. You probably want to fix that :-)
Jul 18 '05 #3
> In article <pa************ *************** *@hotmail.com>,
[snip]

This works, and is pretty straight-forward:

source = ['1','2','7','8' ,'12','13']
temp = []

while source:
x = source.pop(0)
y = source.pop(0)
temp.append ('{%s,%s}' % (x, y))

result = ','.join (temp)
print result

[snip]

How long is "much longer", and how important is it that this runs fast?
The code above runs in O(n). You can probably play some tricks to tweak
the speed a little, but in the big picture, you're not going to do any
better than O(n).


Are you sure? Did you consider the complexity of list.pop(0)?

Jp
Jul 18 '05 #4
I wrote:
The code above runs in O(n).

Jp Calderone <ex*****@divmod .com> wrote: Are you sure? Did you consider the complexity of list.pop(0)?


I'm assuming list.pop() is O(1), i.e. constant time. Is it not?

Of course, one of my pet peeves about Python is that the complexity of
the various container operations are not documented. This leaves users
needing to guess what they are, based on assumptions of how the
containers are probably implemented.
Jul 18 '05 #5

"Roy Smith" <ro*@panix.co m> wrote in message
news:ro******** *************** @reader1.panix. com...
Are you sure? Did you consider the complexity of list.pop(0)?
I'm assuming list.pop() is O(1), i.e. constant time. Is it not?


Yes, list.pop() (from the end) is O(1) (which is why -1 is the default arg
;-).
However, list.pop(0) (from the front) was O(n) thru 2.3.
The listobject.c code has been rewritten for 2.4 and making the latter O(1)
also *may* have been one of the results. (This was discussed as desireable
but I don't know the result.)
Of course, one of my pet peeves about Python is that the complexity of
the various container operations are not documented.


So volunteer a doc patch, or contribute $ to hire someone ;-).

Terry J. Reedy

Jul 18 '05 #6
[Terry Reedy]
However, list.pop(0) (from the front) was O(n) thru 2.3.
The listobject.c code has been rewritten for 2.4 and making the latter O(1)
also *may* have been one of the results. (This was discussed as desireable
but I don't know the result.)


Didn't happen -- it would have been too disruptive to the basic list
type. Instead, Raymond Hettinger added a cool new dequeue type for
2.4, with O(1) inserts and deletes at both ends, regardless of access
pattern (all the hacks suggested for the base list type appeared to
suffer under *some* pathological (wrt the hack in question) access
pattern). However, general indexing into a deque is O(N) (albeit with
a small constant factor). deque[0] and deque[-1] are O(1).

[Roy Smith]
Of course, one of my pet peeves about Python is that the complexity of
the various container operations are not documented.


Lists and tuples and array.arrays are contiguous vectors, dicts are
hash tables. Everything follows from that in obvious ways -- butyou
already knew that. The *language* doesn't guarantee any of it,
though; that's just how CPython is implemented. FYI, the deque type
is implemented as a doubly-linked list of blocks, each block a
contiguous vector of (at most) 46 elements.
Jul 18 '05 #7
Tim Peters <ti********@gma il.com> wrote:
Lists and tuples and array.arrays are contiguous vectors, dicts are
hash tables. Everything follows from that in obvious ways -- but you
already knew that.


OK, so it sounds like you want to reverse() the list before the loop,
then pop() items off the back. Two O(n) passes [I'm assuming reverse()
is O(N)] beats O(n^2).
Jul 18 '05 #8
[Roy Smith]
OK, so it sounds like you want to reverse() the list before the loop,
then pop() items off the back. Two O(n) passes [I'm assuming reverse()
is O(N)]
Yes.
beats O(n^2).


Absolutely. Note that Peter Otten previously posted a lovely O(N)
solution in this thread, although it may be too clever for some
tastes:
from itertools import izip
items = ['1','2','7','8' ,'12','13']
it = iter(items)
",".join(["{%s,%s}" % i for i in izip(it, it)]) '{1,2},{7,8},{1 2,13}'

Jul 18 '05 #9
Tim Peters <ti********@gma il.com> wrote:
Note that Peter Otten previously posted a lovely O(N)
solution in this thread, although it may be too clever for some
tastes:
from itertools import izip
items = ['1','2','7','8' ,'12','13']
it = iter(items)
",".join(["{%s,%s}" % i for i in izip(it, it)])

'{1,2},{7,8},{1 2,13}'


Personally, I'm not a big fan of clever one-liners. They never seem
like such a good idea 6 months from now when you're trying to figure out
what you meant when you wrote it 6 months ago.
Jul 18 '05 #10

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

Similar topics

0
4125
by: David Furey | last post by:
Hi, I am using the XSLT document to filter records from an XML document The XSL is shown below: I have a parameter named "search-for" that is used to bring back a list of Vendor Names that start with this parameter. The list works as I want for alpabetical letters. Setting the parameter to 'a' brings back a list of vendors beginning
5
1781
by: Daniel Crespo | last post by:
Is there a built-in method for transforming (1,None,"Hello!") to 1,None,"Hello!"? Thanks
4
1933
by: Showjumper | last post by:
I am using the NITF DTD for my xml files and i need to use 2 xsl files to do the transform: one for the <body.head> and the second for the <body.content>. I've got this so far for transforming using 1 xsl file: Dim doc As New XmlDocument doc.LoadXml(xmlText) Dim xslDoc As New XslTransform xslDoc.Load(xslpath) Dim sw As New StringWriter xslDoc.Transform(doc, Nothing, sw, Nothing)
3
4875
by: Sergio Otoya | last post by:
Hi all, I need to transform an xml document, using xsl to a HTML output. I can do this successfully using the XslTransform class as below: Dim oTrans As New XslTransform oTrans.Load(sXSLPath) oTrans.Transform(sXMLPath, "c:\trans.htm")
4
2027
by: Cathie | last post by:
Hi All, I am trying to get my style sheet to work. It works fine in IE but I can't get it to work in .net. Below is the function I use for transforming, where advancedOptionsFile is the path to the file containing an XML document required by the transformation, and xmlSimplified is the XML document to trasform. ---------------------------------------------------------------------------- -------------------------------
6
4674
by: Adam Clauss | last post by:
I have a list of points (their coming in as decimal types, I can convert to PointF) that I am trying to draw to a form. Unfortunately, the coordinate system these points are coming from is not like Windows Forms use. Instead of (0,0) being the top left, (0,0) is in the "standard" graph position in the center of the coordinate plane. (So we have positive and negative values on both the x- and y- axis). Is there a "good" way to convert...
0
1091
by: Gustaf | last post by:
I'd like to see if someone found a natural explanation to this. I have this method for transforming docs: /** * Transforms an XmlDocument object with an XSL file, and returns * another XmlDocument object. If something bad happens, null is * returned instead. */ private XmlDocument Transform (string xml, string xsl) {
5
1274
by: james_027 | last post by:
hi, i have a list from a resultset like this 1,"Chicago Bulls",,,"" 2,"Cleveland Caveliers",,,"" 4,"Detroit Pistons",1,"23686386.35" 4,"Detroit Pistons",2,"21773898.07" 4,"Detroit Pistons",3,"12815215.57" 4,"Detroit Pistons",4,"48522347.76" 4,"Detroit Pistons",5,"28128425.99"
1
2063
by: scmorgan | last post by:
Hi All, I am trying to come up with a solution for transforming a complex type ie xml ... <document> <label> This is a <highlight> string</highlight> </label>
0
8999
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
9575
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...
1
9338
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9256
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...
1
6803
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6080
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
4712
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...
2
2798
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2223
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.