python - 在 python 中搜索二维数组 - 最佳方法+缩进错误

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

我在 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

最佳答案

这里的主要问题是 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 - 在 python 中搜索二维数组 - 最佳方法+缩进错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44435679/

相关文章:

python - 使用 anaconda3 python 3.5 安装 Tensorflow 得到 'Read timed out error"

python - 问题是生成一个带有字典的表。为什么键和值使用方括号和大括号?

python - 使用 GitPython 反向读取提交

c - 出现段错误但不知道如何修复它

c++ - 如何在现代C++中创建庞大的数组?

javascript - 按层次结构级别嵌套对象数组 JavaScript/TypeScript

python - 如何根据条件在 qweb 报告上隐藏或显示 python 函数的内容?

python - DataFrame 采用列的并集并保留找到第一个非 NaN 值

python - 在文本小部件中重新绑定(bind) "select all"

python - 计算列表中子列表的特定索引中值的实例,但每个列表只计算一次