jerrizzy
jerrizzy

Reputation: 35

python skipping the next index in a loop if a condition is met in 2 lists

I'm new at python so I'm not sure if this is the best approach.

I have 2 lists with the same amount of values. I want to compare the values of each index from the 2 lists i.e index 1 of player 1 to player 2, index 2 of player 1 to player 2 and so on.

if index 1 of player 1 to player 2 values are matched add 2 points and skip the next index on both lists. Having trouble figuring out how to skip the next index if both values of index 1 are a matched. Please help.

This is my code:

player1 = ['yes', 'deal', 'no', 'no deal', 'no', 'deal']
player2 = ['yes', 'no deal', 'yes', 'deal', 'no', 'deal']

count = 0
skip_count = 0

for i in range(len(player1)):
    if player1[i] == player2[i]:
        count += 2
        skip_count = 0
    else:
        count += 1

when I print count, it doesn't skip as I want it to any thoughts?

Upvotes: 2

Views: 1474

Answers (2)

Iain Shelvington
Iain Shelvington

Reputation: 32244

You can use zip() to create a generator that will iterate over the two lists in pairs. When the condition is met you can use next() to generate the next pair in the iterator "skipping" over that pair:

player1 = ['yes', 'deal', 'no', 'no deal', 'no', 'deal']
player2 = ['yes', 'no deal', 'yes', 'deal', 'no', 'deal']
pairs = zip(player1, player2)
count = 0
for a, b in pairs:
    if a == b:
        count += 2
        next(pairs, None)
    elif a != b:
        count += 1
        comp = next(pairs, True)
        if 'deal' and 'deal' in comp:
            count += -2
            break
        elif 'no deal' and 'deal' in comp:
            count += -1
            break
        elif 'no deal' and 'no deal' in comp:
            count += 0
            break
        else:
            break
    else:
        break
print(count)

Upvotes: 3

kmmanoj
kmmanoj

Reputation: 196

Use a while loop. One could have better control over the sentinel value (or) iterator value (the variable that controls entry to the loops implementation).

player1 = ['yes', 'deal', 'no', 'no deal', 'no', 'deal']
player2 = ['yes', 'no deal', 'yes', 'deal', 'no', 'deal']

cap = len(player1)
i = 0 # sentinel

while i < cap:
    if player1[i] == player2[i]:
        i += 1 # handle the skip
    i += 1 # handle next

''' In simpler terms
while i < cap:
    if player1[i] == player2[i]:
        i += 2
    else :
        i += 1
'''

Upvotes: 2

Related Questions