Pangu
Pangu

Reputation: 3819

How do you start at the same element in a nested for loop?

I'm having difficulty understanding how to make a nested for loop start at the "same" element.

Here is part of my code:

for elem1 in sentence2:
    for elem2 in bigram_list:
        if (elem1 == vocab_list[int(elem2[0]) - 1]):
            file.write("elem1: " + elem1 + "\n")
            file.write("vocab: " + vocab_list[int(elem2[0]) - 1] + "\n")
            index3 = index3 + 1
            for (sameElem2 in bigram_list):
                if (sentence2[index3] == vocab_list[int(sameElem2[1]) - 1]

The thing is, each elem2 in bigram_list contains indices elem2[0], elem2[1], elem2[2]

I'm trying to check whether an element at elem[0] in bigram_list is equal to another element in my sentence2_list, and if it does, I want to be able to start looping through the next index, i.e. elem2[1] but still be at that same element in the bigram_list and check if it's equal to the next element in the sentence2_list

But that's where I'm stuck. I want to go forward, not backwards :)

Upvotes: 0

Views: 64

Answers (2)

barak manos
barak manos

Reputation: 30146

You can use indexing instead:

for elem1 in sentence2:
    for i in range(0,len(bigram_list)):
        elem2 = int(bigram_list[i])-1
        if (elem1 == vocab_list[elem2]):
            file.write("elem1: " + elem1 + "\n")
            file.write("vocab: " + vocab_list[elem2] + "\n")
            if i+1 < len(bigram_list):
                nextElem2 = int(bigram_list[i+1])-1
                index3 = index3 + 1 # Make sure that you want to increment 'index3' here and not inside the 'if'
                if sentence2[index3] == vocab_list[nextElem2]:
                    ...

Upvotes: 0

Slater Victoroff
Slater Victoroff

Reputation: 21934

If I'm understanding correctly, you want to change the starting point of your iteration as you go. If that's so, you can achieve this through some simple slicing:

for i, elem1 in enumerate(bigram_list):
    for elem2 in bigram_list[i:]:
        # Do something

For a bit of explanation, enumerate is a python function that simply returns both the index currently used, and the element in a single tuple, meaning you can access the two as done above.

Upvotes: 3

Related Questions