nested looping

Terry Reedy tjreedy at udel.edu
Wed Apr 8 17:51:53 EDT 2009


PK wrote:
> So I'm trying to see whats the cleanest way to do this:
> 
> I have a
> 
> checklist = [ax, bx, by, cy  ..] (a combination of a,b,c with x and y,
> either both on one)

Since you will be repeatedly looking for items in checklist, I suggest 
making it a set instead.

> allist = [a,b,c,....]
> xlist = [x, y, ..]
> 
> now I wanna loop through alist and xlist and see if the combination
> exists in checklist
> 
> so something like,
> 
> for alpha in alist:
>     for xy in xlist:
>         if alpha+xy not in checklist:
>             missing.append(alpha)

This will append alpha multiple times.  Not what you want.

> now the problem is I want to include alpha in missing list only if
> none of the combinations from xlist with alpha are in checklist.

     for xy in xlist:
       if alpha+xy in checklist: break
     else:
       missing.append(alpha) # or missing.add(alpha) if missing a set

tjr




More information about the Python-list mailing list