我在 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. 有人可以参考这个问题清楚地解释 identatation 以及为什么总是输出第二个“未找到”。 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
原文由 Compoot 发布,翻译遵循 CC BY-SA 4.0 许可协议
这里的主要问题是
break
只退出最内层循环。因此,如果找到一个元素,break
将跳过检查同一列中的其他元素,但外循环仍将前进到下一行。你真正想要的是:(注意另一个中断)或者,可能是使用函数的更具可读性的解决方案:
编辑: 我刚刚想到可以在没有标志变量或函数的情况下编写它,但这不是一种特别优雅的方式。尽管如此,为了完整起见,您在这里:
continue
语句只会在内部循环 没有 被break
退出时执行,它会将外部循环推进到下一行;否则第二个break
将结束外循环。