Home > Software engineering >  Compare Neighboring Elements in an Array of Lists - Python 3.4.3
Compare Neighboring Elements in an Array of Lists - Python 3.4.3

Time:05-30

Compare Last Element of First List, to the First Element of the List Next to its right, or its "Neighbor" in Python 3.4.3

Basically, what im doing is looping through each list and pulling out the first and last elements and putting them all into one list. Then, I take that list and shift it all down one and slap the last element in front and zip the original and that sliced one together. I compare the first and second element of each tuple that is produced. I need all of the elements to be equal, or at least I need to check for that condition.


arr = [ [9, 2, 3, 4], [4, 1], [1, 1, 1], [1, 2, 5, 7, 9] ]
         ^            ==                              ^     
#       it has to compare the first of the first and the last of the last

arr = [ [9, 2, 3, 4], [4, 1], [1, 1, 1], [1, 2, 5, 7, 9] ]
                  ^    ^  ^    ^     ^    ^          
#       it has to compare all the elements that "touch", or are next to each other 

Incorrect Output (that I produce)

[(9, 9), (4, 9), (4, 4), (1, 4), (1, 1), (1, 1), (1, 1), (9, 1)]
           
#          (4, 9)         (1, 4) and   (1,1 count of 2 not 3)     (9, 1) 
#          shouldn't be in the answer 

Should Produce:

[(9, 9), (4, 4), (1, 1), (1, 1), (9, 1)] #edited

Source code

def check(arr):

    res = []
    for l in lst:
    front, back = l[0], l[-1]
    res.append(front)
    res.append(back)
    z = zip(temp, [res[-1]]   res[:-1])
    print(z) 

check( [ [9, 2, 3, 4], [4, 1], [1, 1, 1], [1, 2, 5, 7, 9] ] )

I see that the problem is that it is taking the first and last elements of the first list in my arr and comparing them. (e.g. [9, 2, 3, 4] is comparing 9 and 4, which it should not. I do not know how to fix this because I do not have a way to check if they are from the same array or not.
I looked at this stack overflow question and some others, but they do not specifically answer my NEEDS. Thanks for the help :)

CodePudding user response:

Assuming you had typo in your expected output, you can use zip:

lst = [[9, 2, 3, 4], [4, 1], [1, 1, 1], [1, 2, 5, 7, 9]]

output = [(xs[-1], ys[0]) for xs, ys in zip((lst[-1], *lst), lst)]
print(output) # [(9, 9), (4, 4), (1, 1), (1, 1)]

CodePudding user response:

If your Python version is 3.10 , consider itertools.pairwise:

>>> arr = [ [9, 2, 3, 4], [4, 1], [1, 1, 1], [1, 2, 5, 7, 9] ]
>>> [(i[-1], j[0]) for i, j in pairwise(arr[-1:]   arr)]
[(9, 9), (4, 4), (1, 1), (1, 1)]

To determine whether they are all the same, use all:

>>> all(i[-1] == j[0] for i, j in pairwise(arr[-1:]   arr))
True
  • Related