473,695 Members | 2,278 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

list comprehension

Hello,

Trying to change a string(x,y values) such as :

s = "114320,698 08 114272,69920 113568,71600 113328,72272"

into (x,-y):

out = "114320,-69808 114272,-69920 113568,-71600 113328,-72272"

I tried this:

print [(a[0],-a[1] for a in x.split(',')) for x in e]

But it doesn't work. Can anyone suggest why or suggest an alternative
way? The text strings are significantly bigger than this so performance
is important.

TIA,

Guy
Jul 18 '05 #1
11 2485
In article <c7**********@l ust.ihug.co.nz> ,
Guy Robinson <gu*@NOSPAM.r-e-d.co.nz> wrote:

Trying to change a string(x,y values) such as :

s = "114320,698 08 114272,69920 113568,71600 113328,72272"

into (x,-y):

out = "114320,-69808 114272,-69920 113568,-71600 113328,-72272"

I tried this:

print [(a[0],-a[1] for a in x.split(',')) for x in e]

But it doesn't work. Can anyone suggest why or suggest an alternative
way? The text strings are significantly bigger than this so performance
is important.


When in doubt, break a problem into smaller steps. Let me play Socrates
for a minute: what's the first step in working with your dataset?
--
Aahz (aa**@pythoncra ft.com) <*> http://www.pythoncraft.com/

Adopt A Process -- stop killing all your children!
Jul 18 '05 #2
This works I was just wondering if something could be written more
concisely and hopefully faster:

s = "114320,698 08 114272,69920 113568,71600 113328,72272"
e = s.split(' ')
out =''
for d in e:
d =d.split(',')
out +='%s,%d ' %(d[0],-int(d[1]))
print out

Guy

Aahz wrote:
In article <c7**********@l ust.ihug.co.nz> ,
Guy Robinson <gu*@NOSPAM.r-e-d.co.nz> wrote:
Trying to change a string(x,y values) such as :

s = "114320,698 08 114272,69920 113568,71600 113328,72272"

into (x,-y):

out = "114320,-69808 114272,-69920 113568,-71600 113328,-72272"

I tried this:

print [(a[0],-a[1] for a in x.split(',')) for x in e]

But it doesn't work. Can anyone suggest why or suggest an alternative
way? The text strings are significantly bigger than this so performance
is important.

When in doubt, break a problem into smaller steps. Let me play Socrates
for a minute: what's the first step in working with your dataset?

Jul 18 '05 #3
On Mon, May 10, 2004 at 12:32:20PM +1200, Guy Robinson wrote:
Hello,

Trying to change a string(x,y values) such as :

s = "114320,698 08 114272,69920 113568,71600 113328,72272"

into (x,-y):

out = "114320,-69808 114272,-69920 113568,-71600 113328,-72272"

I tried this:

print [(a[0],-a[1] for a in x.split(',')) for x in e]

But it doesn't work. Can anyone suggest why or suggest an alternative
way? The text strings are significantly bigger than this so performance
is important.


It has several syntax errors; (a[0],-a[1] for a in x.split(',')) is not a
valid expression because list comprehensions are bracketed by square
brackets, not parentheses. Also, the first part of a list comprehension,
the expression to calculate each element, needs to be in parens to if it has
a comma, so that the parser can disambiguate it from an ordinary list.

I also don't know where you got 'e' from. Is it 's', or 's.split()'?

If list comprenhensions grow unwieldy, just use a for loop. They're
probably easier to read than a list comprehension that takes you ten minutes
to concoct, and performance is almost identical. For the sake of answering
your question, though, here's a expression that does what you ask:
s = "114320,698 08 114272,69920 113568,71600 113328,72272"
s.replace(',',' ,-') '114320,-69808 114272,-69920 113568,-71600 113328,-72272'

You could do this with list comprehensions, e.g.:
' '.join(['%s,-%s' % tuple(x) for x in [pairs.split(',' ) for pairs in s.split(' ')]])

'114320,-69808 114272,-69920 113568,-71600 113328,-72272'

But I don't really see the point, given the way you've described the
problem.

-Andrew.
Jul 18 '05 #4
Guy Robinson wrote:
This works I was just wondering if something could be written more
concisely and hopefully faster:
s = "114320,698 08 114272,69920 113568,71600 113328,72272"
e = s.split(' ')
out =''
outl = []
for d in e:
d =d.split(',')
out +='%s,%d ' %(d[0],-int(d[1]))
outl.append(s) # where s is the string you construct
out = ' '.join(outl)
print out

Guy


It's faster to collect strings in a list and join them later than to
concatenate strings one by one.

Also, do you have to convert d[1] to int? If you are sure that it is
always a positive integer, you can do '%s,-%s' % (d[0],d[1]).

In fact you could even try to replace ',' with ',-' instead of splitting
the string at all. Of course it depends on what the format of your
incoming string is.

--
Shalabh
Jul 18 '05 #5
In article <c7**********@l ust.ihug.co.nz> ,
Guy Robinson <gu*@NOSPAM.r-e-d.co.nz> wrote:

This works I was just wondering if something could be written more
concisely and hopefully faster:

s = "114320,698 08 114272,69920 113568,71600 113328,72272"
e = s.split(' ')
out =''
for d in e:
d =d.split(',')
out +='%s,%d ' %(d[0],-int(d[1]))
print out


Performance I can understand (which Shalabh addressed quite nicely), but
why do you care about compressing the source code? This is simple,
straightforward , and easy to read; surely that's more important than
saving a few bytes?
--
Aahz (aa**@pythoncra ft.com) <*> http://www.pythoncraft.com/

Adopt A Process -- stop killing all your children!
Jul 18 '05 #6
Guy Robinson <gu*@NOSPAM.r-e-d.co.nz> wrote:
This works I was just wondering if something could be written more
concisely and hopefully faster:

s = "114320,698 08 114272,69920 113568,71600 113328,72272"
e = s.split(' ')
out =''
for d in e:
d =d.split(',')
out +='%s,%d ' %(d[0],-int(d[1]))
print out


Well, why not the more obvious: s.replace(',',' ,-')
--
- Tim Roberts, ti**@probo.com
Providenza & Boekelheide, Inc.
Jul 18 '05 #7
Tim Roberts wrote:
Guy Robinson <gu*@NOSPAM.r-e-d.co.nz> wrote:
This works I was just wondering if something could be written more
concisely and hopefully faster:

s = "114320,698 08 114272,69920 113568,71600 113328,72272"
e = s.split(' ')
out =''
for d in e:
d =d.split(',')
out +='%s,%d ' %(d[0],-int(d[1]))
print out


Well, why not the more obvious: s.replace(',',' ,-')


But beware negative numbers:
int("--1") Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: invalid literal for int(): --1
Therefore at least
"123,234 567,-789".replace(", ", ",-").replace( "--", "") '123,-234 567,789'


As to robustness, the OP relying on commas not being followed by a space
seems dangerous, too, if the original data is created manually.

Peter

Jul 18 '05 #8
On Mon, 10 May 2004 12:32:20 +1200, Guy Robinson wrote:
Hello,

Trying to change a string(x,y values) such as :

s = "114320,698 08 114272,69920 113568,71600 113328,72272"

into (x,-y):

out = "114320,-69808 114272,-69920 113568,-71600 113328,-72272"

I tried this:

print [(a[0],-a[1] for a in x.split(',')) for x in e]

But it doesn't work. Can anyone suggest why or suggest an alternative
way? The text strings are significantly bigger than this so performance
is important.

TIA,

Guy


this works:

s = "114320,698 08 114272,69920 113568,71600 113328,72272"

o = [(int(a[0]),-int(a[1])) for a in [b.split(',') for b in s.split(' ')]]
print o

[(114320, -69808), (114272, -69920), (113568, -71600), (113328, -72272)]

Jul 18 '05 #9
s.replace(',',' ,-') HA!!:-)

Thanks Andrew. As usual making it more complicated than it needs to be...

Guy

Andrew Bennetts wrote:
On Mon, May 10, 2004 at 12:32:20PM +1200, Guy Robinson wrote:
Hello,

Trying to change a string(x,y values) such as :

s = "114320,698 08 114272,69920 113568,71600 113328,72272"

into (x,-y):

out = "114320,-69808 114272,-69920 113568,-71600 113328,-72272"

I tried this:

print [(a[0],-a[1] for a in x.split(',')) for x in e]

But it doesn't work. Can anyone suggest why or suggest an alternative
way? The text strings are significantly bigger than this so performance
is important.

It has several syntax errors; (a[0],-a[1] for a in x.split(',')) is not a
valid expression because list comprehensions are bracketed by square
brackets, not parentheses. Also, the first part of a list comprehension,
the expression to calculate each element, needs to be in parens to if it has
a comma, so that the parser can disambiguate it from an ordinary list.

I also don't know where you got 'e' from. Is it 's', or 's.split()'?

If list comprenhensions grow unwieldy, just use a for loop. They're
probably easier to read than a list comprehension that takes you ten minutes
to concoct, and performance is almost identical. For the sake of answering
your question, though, here's a expression that does what you ask:

s = "114320,698 08 114272,69920 113568,71600 113328,72272"
s.replace(' ,',',-')
'114320,-69808 114272,-69920 113568,-71600 113328,-72272'

You could do this with list comprehensions, e.g.:

' '.join(['%s,-%s' % tuple(x) for x in [pairs.split(',' ) for pairs in s.split(' ')]])


'114320,-69808 114272,-69920 113568,-71600 113328,-72272'

But I don't really see the point, given the way you've described the
problem.

-Andrew.

Jul 18 '05 #10

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

Similar topics

23
40629
by: Fuzzyman | last post by:
Pythons internal 'pointers' system is certainly causing me a few headaches..... When I want to copy the contents of a variable I find it impossible to know whether I've copied the contents *or* just created a new pointer to the original value.... For example I wanted to initialize a list of empty lists.... a=, , , , ] I thought there has to be a *really* easy way of doing it - after a
35
2968
by: Moosebumps | last post by:
Does anyone here find the list comprehension syntax awkward? I like it because it is an expression rather than a series of statements, but it is a little harder to maintain it seems. e.g. you could do: result = for element in list: if element == 'blah':
7
2269
by: Chris P. | last post by:
Hi. I've made a program that logs onto a telnet server, enters a command, and then creates a list of useful information out of the information that is dumped to the screen as a result of the command. Here's a generic version of the code in question: ##### # Prior code opens telnet connection "tn" and logs in. tn.read_until('> ') tn.write('THE COMMAND IS HERE\n')
6
1971
by: jena | last post by:
hello, when i create list of lambdas: l=] then l() returns 'C', i think, it should be 'A' my workaround is to define helper class with __call__ method: class X: def __init__(self,s): self.s=s def __call__(self): return self.s.upper() l=]
18
460
by: a | last post by:
can someone tell me how to use them thanks
4
1809
by: Gregory Guthrie | last post by:
Sorry for a simple question- but I don't understand how to parse this use of a list comprehension. The "or" clauses are odd to me. It also seems like it is being overly clever (?) in using a lc expression as a for loop to drive the recursion. Thanks for any insight! Gregory
4
1564
by: bullockbefriending bard | last post by:
Given: class Z(object): various defs, etc. class ZList(list): various defs, etc. i would like to be able to replace
11
7047
by: beginner | last post by:
Hi, Does anyone know how to put an assertion in list comprehension? I have the following list comprehension, but I want to use an assertion to check the contents of rec_stdl. I ended up using another loop which essentially duplicates the functions of list comprehension. It just look like a waste of coding and computer time to me. I just wish I could put the assertions into list comprehensions.
10
15021
by: Debajit Adhikary | last post by:
I have two lists: a = b = What I'd like to do is append all of the elements of b at the end of a, so that a looks like: a =
4
3054
by: beginner | last post by:
Hi All, If I have a list comprehension: ab= c = "ABC" print c
0
8649
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
9004
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...
1
8864
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
8838
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
7683
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...
1
6506
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
5842
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();...
1
3025
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
1986
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.