Assertion in list comprehension

beginner zyzhu2000 at gmail.com
Wed Aug 1 12:24:03 EDT 2007


On Aug 1, 11:09 am, "danmcle... at yahoo.com" <danmcle... at yahoo.com>
wrote:
> On Aug 1, 9:37 am, beginner <zyzhu2... at gmail.com> wrote:
>
>
>
>
>
> > Hi,
>
> > Does anyone know how to put an assertion in list comprehension? I have
> > the following list comprehension, but I want to use an assertion to
> > check the contents of rec_stdl. I ended up using another loop which
> > essentially duplicates the functions of list comprehension. It just
> > look like a waste of coding and computer time to me.
>
> > I just wish I could put the assertions into list comprehensions.
>
> >         x=[(rec_stdl[0].st/10000.0,
> >             rec_stdl[0].cl,
> >             rec_stdl[0].bb,
> >             rec_stdl[0].bo,
> >             rec_stdl[1].bb,
> >             rec_stdl[1].bo,
> >             rec_stdl[0].ex
> >            )
> >            for rec_stdl in rec_by_ex if len(rec_stdl)==2
> >         ]
>
> >         #duplicated loop
> >         if __debug__:
> >             for rec_stdl in rec_by_ex:
> >                 l=len(rec_stdl)
> >                 assert(l<=2 and l>0)
> >                 if l==2:
> >                     assert(rec_stdl[0].c=="C" and rec_stdl[1].c=="P")
> >                     assert(rec_stdl[0].ex==rec_stdl[1].ex)
> >                     assert(rec_stdl[0].st==rec_stdl[1].st)
> >                     assert(rec_stdl[0].cp==rec_stdl[1].cp)
>
> > Thanks,
> > Geoffrey
>
> Can't you just call a function from within your list comprehension and
> do whatever you want for each item? Something like this (not tested):
>
> def checker(item):
>     assert(len(item) <= 2 and len(item) > 0)
>     if len(item) == 2:
>         assert(item[0].c == "C" and item[1].c == "P"
>
>     return len(item) == 2
>
> x = [whatever for item in all_items if checker(item = item)]- Hide quoted text -
>
> - Show quoted text -

Good idea! Thank you!




More information about the Python-list mailing list