Newbie: list comprehension troubles..

Francesco Bochicchio bieffe62 at gmail.com
Mon Aug 24 07:42:29 EDT 2009


On 24 Ago, 01:27, mm <matta... at gmail.com> wrote:
> Hi, I'm trying to replace this...
>
>         # this works but there must be a more pythonic way, right?
>         tlist = []
>         for obj in self.objs:
>             t = obj.intersect(ray)
>             if (t != None):
>                 tlist.append((obj,t))
>
> with a list comprehension- can it be done?
>
> What I need to do is iterate over a list of graphics primitives and
> call their intersect method. If the returned t value is not None then
> I want to store the obj refernence and its t value in a list of tuples
> for further processing. I've tried stuff like ...
>
>         tlist = [(obj,t) for obj,t in (self.objs, obj.intersect(ray))
> if (t != None)]
>         tlist = [(obj,t) for obj in self.objs for t in obj.intersect
> (ray) ]
>         print ">>> ",len(tlist), tlist
>
> but they don't work. Any help greatly appreciated. matt

What about this:

def intersections(objlist, ray):
     for obj in objlist: yield obj, obj.intersect(ray)
tlist = [(obj, t) in intersections(self.objs, ray) if t != None ]

It is still quite readable but a bit more compact. More efficient?
Maybe.

Ciao
----
FB





More information about the Python-list mailing list