list comprehension
Shalabh Chaturvedi
shalabh at cafepy.com
Sun May 9 21:40:56 EDT 2004
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
More information about the Python-list
mailing list