473,386 Members | 1,828 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

list comprehension

Hello,

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

s = "114320,69808 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 2459
In article <c7**********@lust.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,69808 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**@pythoncraft.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,69808 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**********@lust.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,69808 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,69808 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,69808 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,69808 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**********@lust.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,69808 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**@pythoncraft.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,69808 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,69808 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,69808 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,69808 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,69808 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,69808 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
On Mon, 10 May 2004 12:32:20 +1200, Guy Robinson
<gu*@NOSPAM.r-e-d.co.nz> wrote:
Hello,

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

s = "114320,69808 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.


Seems like this is a very common problem, needing to process a
substring within a long list of strings. I like the way Ruby handles
these problems. Maybe a future version of Python could do this:

print s.split(' ').map().split(',').reflecty().join(' ')

You would need to define the reflecty() function, but the others
should be standard. Depending on how much variation you expect in the
input data, reflecty() could do whatever checking is necessry to avoid
the problems other posters have mentioned. Assuming the inputs are
valid string representations of numbers (i.e. no double minuses,
etc.), a simple definition could be:

def reflecty():
x,y = __self__ # a two-string list
if y[0] == '-':
return [ x, y[1:] ]
else:
return [ x, '-' + y ]

The above syntax is neither Ruby nor Python, but the idea of handling
complex sequences of string operations step-by-step, left-to-right was
inspired by Ruby. See http://userlinux.com/cgi-bin/wiki.pl?RubyPython
for a comparison of Ruby and Python string operations.

-- Dave

Jul 18 '05 #11
David MacQuigg wrote:
<gu*@NOSPAM.r-e-d.co.nz> wrote:
Trying to change a string(x,y values) such as :

s = "114320,69808 114272,69920 113568,71600 113328,72272"

into (x,-y):

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


if you can count on there being no spaces between the x,y pairs, this works:

" ".join([ "%s,%i"%(y[0], -int(y[1]) ) for y in [x.split(",") for x in
s.split()] ])

Though I don't think I'd do it as a one liner.

-Chris
--
Christopher Barker, Ph.D.
Oceanographer

NOAA/OR&R/HAZMAT (206) 526-6959 voice
7600 Sand Point Way NE (206) 526-6329 fax
Seattle, WA 98115 (206) 526-6317 main reception

Ch**********@noaa.gov
Jul 18 '05 #12

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

Similar topics

23
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*...
35
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...
7
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...
6
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...
18
by: a | last post by:
can someone tell me how to use them thanks
4
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...
4
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
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...
10
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
by: beginner | last post by:
Hi All, If I have a list comprehension: ab= c = "ABC" print c
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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,...
0
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...

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.