How to iterate through python array and compare element with previous element?

I have problems with an array in python. I want to go through it and compare element n with element n-1. For instance:

 [(11, 11), (11, 10), (11, 9), (11, 8), (11, 7), (11, 6), (11, 5),
  (11, 4), (10, 4), (9, 4), (8, 4), (8, 5), (7, 5), (6, 5), (5, 5),
  (4, 5), (3, 5), (3, 4), (3, 3), (2, 3), (1, 3), (1, 2), (1, 1), (1, 0)]

Using the array above, I want to apply the following steps / logic:

  • 0,1 = right

  • 1.0 = down

  • -1.0 = up

  • 0, -1 = left

So, if the element of the array that we are looking at is the first value smaller than the previous one, I want to print.

Thus, the result for the array above will be (provided that the beginning is always equal to 0.0)

[Start, down, right, right, right, down, down, right, right, down, 
down, down, down, down, left, down, down, down, right, right, right, 
right, right, right, right] 

It's hard to explain, sorry if this is a bit confusing. Also, an element will never be diagonal, so that it will never receive from (1,1) to (2,2), one of the two sub-elements will change at any given time.

+4
source share
2

, coords, :

steps = [(x2-x1, y2-y1) for ((x1, y1), (x2, y2)) in  zip(coords, coords[1:])]

:

  • coords [1:] , .
  • zip (, [1:])
  • n , zip n-1, zip . , - , , ( Ev. Kounis ).

EDIT: , , :

coords = [(11, 11), (11, 10), (11, 9), (11, 8), (11, 7), (11, 6),
          (11, 5), (11, 4), (10, 4), (9, 4), (8, 4), (8, 5), (7, 5),
          (6, 5), (5, 5), (4, 5), (3, 5), (3, 4), (3, 3), (2, 3),
          (1, 3), (1, 2), (1, 1), (1, 0)]

movements = {
        (0, 1):  'right',
        (1, 0):  'down',
        (-1, 0): 'up',
        (0, -1): 'left'
        }

steps = [movements[(x2-x1, y2-y1)]
         for ((x1, y1), (x2, y2)) in zip(coords, coords[1:])]
+5

You can always just get the index i-1for the previous item starting with i=1:

from operator import sub

lst = [(11, 11), (11, 10), (11, 9), (11, 8), (11, 7), (11, 6), (11, 5), (11, 4), (10, 4), (9, 4), (8, 4), (8, 5), (7, 5), (6, 5), (5, 5), (4, 5), (3, 5), (3, 4), (3, 3), (2, 3), (1, 3), (1, 2), (1, 1), (1, 0)]

d = {(0, 1):'right', (1, 0): 'down', (-1, 0): 'up', (0, -1): 'left'}

result = [d[tuple(map(sub, lst[i], lst[i-1]))] for i in range(1, len(lst))]

print(result)
# ['left', 'left', 'left', 'left', 'left', 'left', 'left', 'up', 'up', 'up', 'right', 'up', 'up', 'up', 'up', 'up', 'left', 'left', 'up', 'up', 'left', 'left', 'left']
+1
source

Source: https://habr.com/ru/post/1693824/


All Articles