list comprehension
Andrew Bennetts
andrew-pythonlist at puzzling.org
Sun May 9 20:56:53 EDT 2004
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.
More information about the Python-list
mailing list