我已经创建了如下二维数组(名单列表):搜索在python的二维数组 - 在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
你别的不匹配if语句的缩进。 – Zeokav
这里有什么声明是:? –
我玩过不同的职位/身份其他:....这是我需要帮助。如果我知道,我不会问!在此先感谢 – MissComputing