Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/magento/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中搜索2d数组-最佳方法+;压痕误差_Python_Arrays_Python 3.x_Search_2d - Fatal编程技术网

在python中搜索2d数组-最佳方法+;压痕误差

在python中搜索2d数组-最佳方法+;压痕误差,python,arrays,python-3.x,search,2d,Python,Arrays,Python 3.x,Search,2d,我用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 colum

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

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

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

答复:

有人提出了如下答案:(我已经试过了)

注意,它也根本不起作用:

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

您似乎是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!")

这应该满足您的要求

matrix=[[1,2,3,4,5,6,7],[8,9,10,11,12,13,14],[15,16,17,18,19,20,21]]
x = 93
bool_value = [True if x in mat else False for mat in matrix]
print('Found' if any(bool_value) else 'Not found')
注意:
any()
如果列表中至少有一个值为True,则返回
True
。 在python中,缩进也充当块分隔符 例如在c/c++中

if(condition){
 do a thing
}
else{
do something else
}
但在python中,缩进充当块分隔符

if (condition):
    do a thing
else:
    do something else
其中四个空格或一个制表符充当块分隔符。因此,如果我用+(这只是为了理解目的)来表示空格

你的想法对吗?而且缩进在代码中是不合适的,这就是为什么每次打印
notfound


编辑:如注释中所述
[如果mat中的x为True,则矩阵中的mat为False]
可以写成
[矩阵中的mat为x]
,但我会让它保持原样供您理解,因为您是python新手。

这里的主要问题是
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")
continue
语句将仅在
break
未退出内部循环时执行,并将外部循环推进到下一行;否则,第二个
中断将结束外循环

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'

如果您要查找的只是矩阵中是否存在该值,那么我将采用另一种方法:

import itertools

matrix=[
     [1,2,3,4,5,6,7],
     [8,9,10,11,12,13,14],
     [15,16,17,18,19,20,21],
       ]

unique_elements = set(itertools.chain(*matrix))
in_matrix = lambda a, set: a in set

print(in_matrix(3, unique_elements))   #True

若你们在矩阵中寻找一个常量元素,你们可以同时利用两个Map和Lambda。我在这里编写了一个简单的代码片段:

y = 44
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
if True in map(lambda x: y in x, matrix):
    print("Found")
else:
    print("There is no {} in the given matrix".format(y))

这必须是在多维数组中查找元素的最简单代码。此外,与此处的其他代码不同,它不受维数的限制。如果省略break语句,也可以继续搜索该元素。

这是另一种方法

    def search(matrix, target):
    r = len(matrix)
    c = len(matrix[0])
    ll = []
    for i in range(0, r*c):
        row = i//c  # division "//" (floor) and division "/" (float)
        col = i % c # remainder
        ll.append(matrix[row][col])

    if(target in ll):
        return True
    else:
        return False


    matrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]]
    target = 0
    print(search(matrix, target))

您的else与if语句的缩进不匹配。对于这里的else语句:?我已经为else使用了不同的位置/标识:……这就是我需要帮助的地方。如果我知道,我就不会问了!提前感谢您上次编辑没有错误-您检查了每个矩阵项的“9”,您刚刚输入的内容根本不起作用-这是我以前尝试过的实现:错误:您要找的是什么数字?9找不到找不到找不到找不到!找不到找不到找不到找不到我不这么认为。如果该
else
匹配
如果
,则将为不等于所查找元素的每个元素打印“未找到”;这显然不是OP所要求的。是的,它正在检查号码,并且每次打印时都找不到。我将修改我的答案。等等-我希望它在没有标记的情况下被修复,以便更好地理解缩进。还是不可能?在VB这样的语言中,执行如此简单的搜索不需要添加额外的复杂性层(标志)。这是一个很好的解决方案,但是
True if x in mat else False
是更简单的
x in mat
的一个过于复杂的版本。这只是“元素”一词的一个快捷方式此解决方案的问题是,它将检查矩阵中的所有元素,即使第一个元素是命中的。对于大型矩阵,效率低下。
val = 4
ar = [[1,2,3],[2,3,4]]
for i in ar:
    if 4 in i:
        print("found")
        break
else:
    print("not found")
    def search(matrix, target):
    r = len(matrix)
    c = len(matrix[0])
    ll = []
    for i in range(0, r*c):
        row = i//c  # division "//" (floor) and division "/" (float)
        col = i % c # remainder
        ll.append(matrix[row][col])

    if(target in ll):
        return True
    else:
        return False


    matrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]]
    target = 0
    print(search(matrix, target))