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

标签 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)]

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

  • 0,1 = 右

  • 1,0 = 向下

  • -1,0 = 向上

  • 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 个子元素之一会在任何给定时间发生变化。

最佳答案

考虑到您的坐标数组称为 coords,您可以:

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

解释:

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

编辑:要制作一个字符串列表来表示所做的步骤,您可以制作一个可能的 Action 字典:

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

关于python - 如何遍历 python 数组并将该元素与前一个元素进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48864197/

相关文章:

python - 如何在Python中调用静音/扬声器控制键。戴尔Latitude E7440

python - 将一维结构化数组转换为二维 numpy 数组

java - 如何从数组中计算唯一的 "mode"?

c# - 以字符串数组形式传入多个参数

java - 传递零大小的数组,保存分配?

loops - Mathematica : Conditional Operations on Lists

python - 迭代 Django Rest API 并获取错误

python - 为 pdf 后端设置 spines 的 capstyle

python - 如何用python隔离maya中的组节点

python - 相关矩阵的滚动平均值