nested looping

P

PK

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 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)

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.

The above will exclude the possibility where ax doesn't exist but ay
or az does exist.

Hope There is a cleaner way to accomplish this.

Thanks in advance,
PK
 
M

Matimus

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 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)

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.

The above will exclude the possibility where ax doesn't exist but ay
or az does exist.

Hope There is a cleaner way to accomplish this.

Thanks in advance,
PK

That code doesn't look too bad. It is fairly readable. There are
several ways to accomplish this though. If you aren't interested in
duplicate values or order then sets would be a good option.

something like this:

missing = set(alpha + xy for alpha in alist for xy in xlist).difference
(checklist)

if you are using 2.6 you could also make use of the product generator
in itertools:

from itertools import product
missing = set(''.join(p) for p in product(alist, xlist)).difference
(checklist)

If you could adapt your code to use tuples instead of strings you
could do it like this:

missing = set(product(alist, xlist)).difference(checklist)




Matt
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,781
Messages
2,569,615
Members
45,294
Latest member
LandonPigo

Latest Threads

Top