在python中搜索2d数组-最佳方法+缩进

2024-06-02 07:03:31 发布

您现在位置:Python中文网/ 问答频道 /正文

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

#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),然后使用以下代码打印“found”(如果找到)和“not found”(如果不在数组中):

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

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

请在此回复: 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

Tags: columnsinyounumberfornotrangeit
3条回答
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'

这里的主要问题是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")

只有当内部循环未被break退出时,continue语句才会执行,并且它会将外部循环推进到下一行;否则,第二个break将结束外部循环。

你好像对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!")

相关问题 更多 >