在由列表python 3组成的矩阵中查找模式 [英] find pattern in matrix made of lists python 3

查看:70
本文介绍了在由列表python 3组成的矩阵中查找模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由列表组成的列表,用于创建一个矩阵,其中大部分都填充有零和其他一些类似的数字

I have a list made of lists, to create a matrix, mostly filled with zeros and some other numbers like this

a = [[0,0,0,1,0,0,0,0],
     [3,0,0,2,1,0,0,0],
     [3,0,0,0,0,1,0,0],
     [3,5,0,4,0,0,0,0]]

我如何制作一个使用该变量的函数,并确定对角线中是否存在重复3次的数字?

how could I make a function that takes that variable, and find if there is a number repeated 3 times in the diagonals?

例如,由于1而返回True.我试图实现这样的功能:

For example that It returns True because of the 1. I tried to implement a function like this:

def find_diagonal(matriz):
    for x in range(len(matrix)):
        for for a in range(len(x)):
            if matriz[x][a] != 0:
                encontrar = matriz[x][a]
                if matriz[x+1][a-1] == encontrar:
                    if matriz[x+2][a-2] == encontrar:
                        return True

并在 if matriz [x] [a]!= 0 之后与其他对角线重复此条件(该对角线寻找指向西南方向的对角线).

and repeat the conditions after the if matriz[x][a] != 0 with the other diagonals (this one looks for the ones directing southwest).

但是除了不能使用每个示例(有时它只能工作一次,然后停止使用同一示例)之外,而且在边缘总是会出现索引错误,因为列表会检查顶部的行.

But besides from not working with every example (sometimes it works once, and stops working with the same example), and at the edges always raises index errors because the list checks for rows over the top.

推荐答案

这是怎么回事:

def check_diag(a, y, x):
  """Take a[y][x] and check if it starts a diagonal"""
  result = False

  # We search downwards, there should be at least 2 more rows
  if y > len(a)-2:
    return False

  if x < len(a[y])-2:
      # Searching SE direction if possible
      result |= (a[y][x] == a[y+1][x+1] == a[y+2][x+2])
  if x > 1:
      # Searching SW direction if possible
      result |= (a[y][x] == a[y+1][x-1] == a[y+2][x-2])

  return result

def has_diag(a):
  # Take all non-zero elements and check if they meet the diag condition
  return any([check_diag(a,y,x)
                for y in range(len(a))
                for x in range(len(a[y]))
                if a[y][x]])

这还会发现更长的对角线,不确定是否要这么做.

This will also find longer diagonals, not sure if you want that.

更多的野蛮"版本,更少的索引魔术:

more "brutal" version with less indexing magic:

def check_diag2(a, y, x):
  """Take a[y][x] and check if it starts a diagonal"""
  try:
    if (a[y][x] == a[y+1][x+1] == a[y+2][x+2]):
      return True
  except IndexError:
    pass

  try:
    if (a[y][x] == a[y+1][x-1] == a[y+2][x-2]):
      return True
  except IndexError:
    pass

  return False

这篇关于在由列表python 3组成的矩阵中查找模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆