list comprehension

David MacQuigg dmq at gain.com
Thu May 13 11:15:57 EDT 2004


On Mon, 10 May 2004 12:32:20 +1200, Guy Robinson
<guy at 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




More information about the Python-list mailing list