user1620716
user1620716

Reputation: 1533

How to iterate through an intersection properly

I am trying to iterate through a series of intersections, where each iteration is the intersection of a new set of rows. I have code that looks somewhat like the following:

    for liness in range(len(NNCatelogue)):
        for iii in [iii for iii, y in enumerate(NNCatelogue[iii]) if y in set(NNCatelogue[liness]).intersection(catid)]:
            print iii, y

NNCatelogue is essentially a 1268 X 12 matrix, and each new iteration of liness calls a new row. If I simply put in the row number that I want (ie: 0, 1, 2...) then I get the expected output (without the for loop in front). The code that is written above gives the following output:

    10 C-18-1064
    4 C-18-1122
    4 C-18-1122
    5 C-18-1122
    5 C-18-1122
    7 C-18-1122
    8 C-18-1122
    9 C-18-1122
    10 C-18-1122
    11 C-18-1122
    6 C-18-1122
    ...

The expected output should be:

  0 C-18-1
  1 C-18-259
  2 C-18-303
  3 C-18-304
  4 C-18-309
  5 C-18-324
  6 C-18-335
  7 C-18-351
  8 C-18-372
  9 C-18-373
  10 C-18-518
  11 C-18-8

Any idea where I might be going wrong? Any help is greatly appreciated!

UPDATE:

I tried a variation of one of the answers, and while it is closer to what I am expecting, it isn't quite there. Here is what I tried:

    counter = 0
    for row in NNCatelogue:
        for value in row:
            if value in set(NNCatelogue[counter]).intersection(catid):
                print counter, value
                counter += 1

The resultant output is:

    0 C-18-1
    1 C-18-324
    2 C-18-351
    3 C-18-4
    4 C-18-5
    5 C-18-6
    6 C-18-7
    7 C-18-8
    8 C-18-9
    9 C-18-10
    10 C-18-11
    11 C-18-12
    12 C-18-13
    ...

So some of the intersections are correct, though it isn't my desired output... Any ideas from here?

Upvotes: 1

Views: 360

Answers (3)

defuz
defuz

Reputation: 27581

As I understand what you need:

counter = 0
for row in NNCatelogue:
    for value in row:
        if value in catid:
            print counter, value
            counter += 1

Upvotes: 1

Kevin Lee
Kevin Lee

Reputation: 718

It appears that the intersection offers a non-numeric sort... Do you get the proper set (just the wrong permutation)?

Upvotes: 0

Achim
Achim

Reputation: 15692

You use iii too often. I cannot even imagine what's exactly going on if you execute this code. Just give your variables useful speaking names and your problem is probably solved.

Upvotes: 5

Related Questions