【问题标题】:searching a 2d array in python - best method + indentation error在python中搜索二维数组-最佳方法+缩进错误
【发布时间】:2017-11-10 03:59:31
【问题描述】:

我在 Python 中创建了以下二维数组(列表列表):

#creating a 2d array (3 rows by 7 columns) and populating it with numbers
matrix=[1,2,3,4,5,6,7],[8,9,10,11,12,13,14],[15,16,17,18,19,20,21]
rows=len(matrix) #finding the max number of rows in the matrix, in this case 3
columns=len(matrix[0]) #finding the max number of columns in each row, 7 in this case

我正在尝试在数组中搜索特定元素(比如数字 9),然后使用以下代码打印“找到”(如果找到)和“未找到”(如果不在数组中):

number=int(input("What number are you looking for?"))
for i in range(rows):
      for j in range(columns):
        if matrix[i][j]==number:
          print("Found it!")
          break
else:
  print("not found")

然而,输出是错误的:

>>What number are you looking for? 9
>>Found it!
>>not found

我有两个问题:1.有人可以解释一下标识,参考这个问题以及为什么总是输出第二个“未找到”。 2.有没有更好更有效的方法来做到这一点,不使用numpy

*注意,这不是重复的,因为我已经搜索了其他条目,但它们并没有完全处理我明确要求的内容。

repl.it 在这里: https://repl.it/IcJ3/3

有人刚刚提出了一个答案如下:(我已经尝试过)

https://repl.it/IcJ3/5 请注意,它也根本不起作用:

number=int(input("What number are you looking for?"))
for i in range(rows):
      for j in range(columns):
        if matrix[i][j]==number:
          print("Found it!")
          break
        else:
          print("not found")

错误的输出,仍然!

What number are you looking for? 9
not found
not found
not found
not found
not found
not found
not found
not found
Found it!
not found
not found
not found
not found
not found
not found
not found

【问题讨论】:

  • 您的 else 与 if 语句的缩进不匹配。
  • 这里还有什么说法:?
  • 我为其他人玩过不同的位置/身份:....这就是我需要帮助的地方。如果我知道,我就不会问了!提前致谢
  • 您上次编辑时没有错误 - 您检查了每个矩阵项的“9”

标签: python arrays python-3.x search 2d


【解决方案1】:

这是一种不同的方法。

    def search(matrix, target):
    r = len(matrix)
    c = len(matrix[0])
    ll = []
    for i in range(0, r*c):
        row = i//c  # division "//" (floor) and division "/" (float)
        col = i % c # remainder
        ll.append(matrix[row][col])

    if(target in ll):
        return True
    else:
        return False


    matrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]]
    target = 0
    print(search(matrix, target))

【讨论】:

    【解决方案2】:
    val = 4
    ar = [[1,2,3],[2,3,4]]
    for i in ar:
        if 4 in i:
            print("found")
            break
    else:
        print("not found")
    

    这必须是在多维数组中查找元素的最简单代码。与此处的其他代码不同,它也不受维数的限制。如果省略了 break 语句,也可以继续搜索该元素。

    【讨论】:

      【解决方案3】:

      如果您正在寻找矩阵中的常量元素,您可以同时利用两个 Map 和 Lambda。我在这里写了一个简单的sn-p代码:

      y = 44
      matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
      if True in map(lambda x: y in x, matrix):
          print("Found")
      else:
          print("There is no {} in the given matrix".format(y))
      

      【讨论】:

        【解决方案4】:

        如果您要寻找的只是该值是否存在于矩阵中,我会走不同的路线:

        import itertools
        
        matrix=[
             [1,2,3,4,5,6,7],
             [8,9,10,11,12,13,14],
             [15,16,17,18,19,20,21],
               ]
        
        unique_elements = set(itertools.chain(*matrix))
        in_matrix = lambda a, set: a in set
        
        print(in_matrix(3, unique_elements))   #True
        

        【讨论】:

          【解决方案5】:

          这里的主要问题是break 只退出最里面的循环。因此,如果找到一个元素,break 将跳过检查同一列中的其他元素,但外部循环仍将前进到下一行。您真正想要的是:

          found = False
          for row in matrix:
              for element in row:
                  if element == number:
                      found = True
                      break
              if found:
                  break
          if found:
              print("Found")
          else:
              print("Not found")
          

          (注意另一个中断) 或者,可能是使用函数的更易读的解决方案:

          def searchfor(matrix, number):
              for row in matrix:
                  for element in row:
                      if element == number:
                          return True
              return False
          
          if searchfor(matrix, number):
              print("Found")
          else:
              print("Not found")
          

          编辑: 我突然想到可以不用标志变量或函数来编写它,但这不是一种特别优雅的方式。不过,为了完整起见,这里是:

          for row in matrix:
              for element in row:
                  if element == number:
                      break
              else:
                  continue
              break
          
          if element == number:
              print("Found")
          else:
              print("Not found")
          

          continue 语句只有在break 没有退出内循环 时才会执行,并将外循环前进到下一行;否则第二个break 将结束外循环。

          【讨论】:

            【解决方案6】:

            这应该可以满足您的要求!

            matrix=[[1,2,3,4,5,6,7],[8,9,10,11,12,13,14],[15,16,17,18,19,20,21]]
            x = 93
            bool_value = [True if x in mat else False for mat in matrix]
            print('Found' if any(bool_value) else 'Not found')
            

            注意:any() 返回True 如果列表中至少有一个值为真。 同样在 python 缩进充当块分隔符 例如在 c/c++ 中

            if(condition){
             do a thing
            }
            else{
            do something else
            }
            

            但在 python 中,缩进充当块分隔符

            if (condition):
                do a thing
            else:
                do something else
            

            其中四个空格或一个制表符充当块分隔符。所以如果我用 + 表示空格(这只是为了理解目的)

            if (condition):
            ++++do a thing
            else:
            ++++if (another_condition):
            ++++++++do_stuff
            ++++else:
            ++++++++do_some_other_stuff
            print("Exited from nested if/else loops")
            

            你的想法对吗?并且缩进在您的代码中不正确,这就是每次打印 not found 的原因。

            编辑: 正如 cmets 中提到的,[True if x in mat else False for mat in matrix] 可以写成 [x in mat for mat in matrix] 但我会保留它,以供您理解,因为您是 python 新手。

            【讨论】:

            • 这是一个很好的解决方案,但True if x in mat else False 是一个简单得多的x in mat 的过于复杂的版本。
            【解决方案7】:
            matrix =[1,2,3,4,5,6,7],[8,9,10,11,12,13,14],[15,16,17,18,19,20,21]
            
            def search_elm(arr, num):
                elm = False
                for i in range(len(arr)):
                  for j in range(len(arr[0])):
                    if arr[i][j] == num:
                      elm = True
                return elm
            

            你可以像这样使用它:

            if search_elm(matrix, 44):
                print 'Found!'
            else:
                print 'Not Found'
            

            【讨论】:

            • 只是“元素”这个词的快捷方式
            • 这个解决方案的问题是它会检查矩阵中的所有元素,即使第一个元素是命中的。对于大型矩阵效率低下。
            【解决方案8】:

            您似乎是 Python 新手。在这种语言中,代码块由指令前的缩进数标识。在您的情况下,您有一个 if 语句,但您的 else 与该 if 语句的缩进不匹配。
            您希望您的代码是这样的 -

            number=int(input("What number are you looking for?"))
            flag = False
            for i in range(rows):
                  for j in range(columns):
                    if matrix[i][j]==number:
                      print("Found it!")
                      flag = True
                      break
            if flag == False:
              print ("Not found!")
            

            【讨论】:

            • 您刚刚输入的内容根本不起作用 - 这是我尝试过的以前的实现:错误:您要找什么号码? 9 没找到 没找到 没找到 没找到 没找到 没找到 没找到 没找到 找到了!未找到 未找到 未找到 未找到 未找到 未找到 未找到
            • 我不这么认为。如果else 匹配if,则将为每个不等于正在查找的元素打印“未找到”;这显然不是 OP 所要求的。
            • 是的,它正在检查数字并在每次不相等时打印未找到。我会修改我的答案。
            • 等待 - 我希望它在没有标志的情况下被修复,以便更好地理解缩进。或者那是不可能的?在像 VB 这样的语言中,不需要添加额外的复杂层(标志)来执行如此简单的搜索
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2018-04-13
            • 2021-06-22
            • 1970-01-01
            • 2021-03-27
            • 2020-01-29
            • 2015-07-12
            • 2019-01-27
            相关资源
            最近更新 更多