nested looping

Luis Alberto Zarrabeitia Gomez kyrie at uh.cu
Wed Apr 8 18:12:50 EDT 2009


Quoting PK <superprad at gmail.com>:

> 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)
> 
> allist = [a,b,c,....]
> xlist = [x, y, ..]
> 
[...]
> 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.

This is untested:

for alpha in alist:
    for xy in xlist:
        if alpha+xy in checklist:
            break
    else:
        missing.append(alpha)

(note that the "else" is for the "for", not the "if")

You could also try the any/all functions from python2.5:

for alpha in alist:
    if not any(alpha + xy in checklist for xy in xlist):
        missing.append(alpha)


Or the really not recommended one-liner:

missing = [alpha for alpha in alist if not any(alpha + xy in checklist for xy in
xlist)]

(remember, all of this is untested)

-- 
Luis Zarrabeitia
Facultad de Matemática y Computación, UH
http://profesores.matcom.uh.cu/~kyrie


-- 
Participe en Universidad 2010, del 8 al 12 de febrero de 2010
La Habana, Cuba 
http://www.universidad2010.cu




More information about the Python-list mailing list