【发布时间】: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