user9794893
user9794893

Reputation: 133

"for" loop x value?

I'm trying to get my second array to print x in increments but reset to zero once the case value changes.

Code:

array = ['2017001677', '2017001677', '2017001621', '2017001621']
array2 = ['2017001677', '2017001621']

x = 0
for case in array:
    for case2 in array2:
        if(case == case2):
            print(case2)
            print(x)
    x = x + 1

Current Output:

2017001677
0
2017001677
1
2017001621
2
2017001621
3

Desired Output:

2017001677
0
2017001677
1
2017001621
0
2017001621
1

How do I accomplish this?

Upvotes: 0

Views: 578

Answers (1)

tdelaney
tdelaney

Reputation: 77367

You can reset the counter for unique values in array by tracking the last-seen value, starting with None

array = ['2017001677', '2017001677', '2017001621', '2017001621']
array2 = ['2017001677', '2017001621']

last_case = None
for case in array:
    if case != last_case:
        x = 0
        last_case = case

    for case2 in array2:
        if(case == case2):
            print(case2)
            print(x)
            x = x + 1

Upvotes: 1

Related Questions