Simple questions on use of objects (probably faq)

Michael ms at cerenity.org
Thu Mar 9 16:11:09 CET 2006


Brian Elmegaard wrote:
...
> The code that runs:
> 
> class Foo:
>     def __init__(self,x):
>         self.x=x
> 
> y=[]
> y.append(Foo(10.0))
> y.append(Foo(110.0))
> y.append(Foo(60.0))
> 
> ys=[]
> y_max=0.0
> y_min=0.0
> 
> for s in y:
>     ys.extend([s.x])
>     y_max=max(s.x,y_max)
>     y_min=min(s.x,y_min)
>     
> yz=[]
> for i in range(len(ys)-1):
>     yz.append(ys[i+1]-ys[i])
> 
> What I hoped I could do:
...
> yz=[y[:-1].x-y[1:].x]

Based on the code that runs, you want* this:

[(y[x+1].x-y[x].x) for x in range(len(y)-1) ]

FWIW, "-" does not work across lists. You could use map if you wanted, but
personally I prefer the explicit loop which you wanted to not use:

> yz=[]
> for i in range(len(ys)-1):
>     yz.append(ys[i+1]-ys[i])

Since personally I find that a lot clearer than:

map(float.__sub__, [X.x for X in y[1:]], [X.x for X in y[:-1] ])

Regards,


Michael.




More information about the Python-list mailing list