如何遍历python数组并将元素与前一个元素进行比较?

时间:2018-02-19 10:34:11

标签: python arrays loops

我在python中遇到一个数组有点麻烦。我想循环遍历它,并将元素n与元素n-1进行比较。例如:

 [(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)]

使用上面的数组,我想应用以下移动/逻辑:

  • 0,1 =对

  • 1,0 = down

  • -1,0 = up

  • 0,-1 =左

因此,如果我们正在查看的数组元素的第一个值小于我想要打印的数据。

所以上面数组的结果是(假设开始总是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] 
如果这有点令人困惑,那么解释如此道歉是一个棘手的问题。此外,元素永远不会对角线,因此它永远不会从(1,1)到(2,2)两个子元素中的一个将在任何给定时间发生变化。

2 个答案:

答案 0 :(得分:5)

考虑到你的坐标数组被称为coords,你可以这样做:

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

说明:

  • coords [1:]表示从第二个开始的所有坐标对
  • zip(coords,coords [1:])使每个坐标与
  • 之前的坐标成对
  • 对于n个corrdinate对的数组,zip将输出n-1个步骤,因为zip的输出长度等于较短的长度其中一个论点。因此,由于第二个列表较短,第一个列表只会被枚举,不包括其最后一个元素(感谢Ev. Kounis建议澄清)

编辑:要制作代表所做步骤的字符串列表,您可以制作可能的动作字典:

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:])]

答案 1 :(得分:1)

您始终可以访问从i-1开始的上一个元素的索引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']