Home > Back-end >  For loop compare previous value in array python
For loop compare previous value in array python

Time:03-31

I am struggling to code a for loop that compares each entry in an array 'a' to the previous one using an if statement and to record its location in the list if the values are different. The array a is a list of 1 and - 1

The array a=[1,1,1,1,-1,-1,-1,1,1,-1] etc. It is a list of randomly ordered 1s and -1 so it could look like 1,1,1,-1,-1,1,1,-1,-1,-1,-1, 1 etc so basically want to find location where it is different to previous one

I'm not entirely sure how you would do this as I am new to python, so any help would be much appreciated. Thanks

So far all I have is

for i in range(len(a)): 
if

CodePudding user response:

Something like

for i in range(1, len(a)):
    if a[i] > a[i-1]:
         #your code here
    elif a[i-1] > a[i]:
         #your code here
    else:
         #your code here

should work.

CodePudding user response:

Can compare using enumerate() with your for loop

Compare to Previous Item in List using enumerate()

a=[1,1,1,1,-1,-1,-1,1,1,-1]

for i, item in enumerate(a):
    #Need to skip first element(when i==0) as a[-1] will return the last value in the array
    if i > 0 and item == a[i-1]:
        print(f"index {i} value:{item} is the same as previous index {i-1}")

Results:

index 1 value: 1 is the same as previous index 0
index 2 value: 1 is the same as previous index 1
index 3 value: 1 is the same as previous index 2
index 5 value:-1 is the same as previous index 4
index 6 value:-1 is the same as previous index 5
index 8 value: 1 is the same as previous index 7

CodePudding user response:

Try this:

[i for i in range(1, len(a)) if a[i-1] != a[i]]
  • Related