有人知道如何使用二维字符串数组进行二分查找吗?

Anybody knows how to do a binary search with a 2d array of strings?

这是我的数组:

import numpy as np

Arr = np.array( [
    ["","A","B","C","D","E","F"],
    ["1","0","0","0","0","0","0"],
    ["2","0","0","0","0","0","0"],
    ["3","0","X","0","0","0","0"],
    ["4","0","0","0","0","0","0"],
    ["5","0","0","0","X","0","0"],
    ["6","X","0","0","0","0","0"],
    ["7","0","0","0","0","0","0"],
    ["8","0","0","0","0","0","0"]
])

我想进行二分查找,但我不知道如何使用字符串数组进行查找。基本上我想看看我所有的“X”所在的位置。

def findRow(a, n, m, k):
#a is the 2d array
#n is the number of rows
#m is the number of columns
#k is the "X"
    l = 0
    r = n - 1
    mid = 0
    while (l <= r) :
        mid = int((l + r) / 2)
         
        # we'll check the left and
        # right most elements
        # of the row here itself
        # for efficiency
        if(k == a[mid][0]): #checking leftmost element
            print("Found at (" , mid , ",", "0)", sep = "")
            return
         
        if(k == a[mid][m - 1]): # checking rightmost element
            t = m - 1
            print("Found at (" , mid , ",", t , ")", sep = "")
            return
        if(k > a[mid][0] and k < a[mid][m - 1]):    # this means the element
                                                    # must be within this row
            binarySearch(a, n, m, k, mid)    # we'll apply binary
                                            # search on this row
            return
        if (k < a[mid][0]):
            r = mid - 1
        if (k > a[mid][m - 1]):
            l = mid + 1
 
def binarySearch(a, n, m, k, x):    #x is the row number
     
    # now we simply have to apply binary search as we
    # did in a 1-D array, for the elements in row
    # number
    # x
    l = 0
    r = m - 1
    mid = 0
    while (l <= r):
        mid = int((l + r) / 2)
         
        if (a[x][mid] == k):
            print("Found at (" , x , ",", mid , ")", sep = "")
            return
        if (a[x][mid] > k):
            r = mid - 1
        if (a[x][mid] < k):
            l = mid + 1
     
    print("Element not found")

这是我尝试过的方法,但这是针对 int 二维数组的。现在我有一个字符串 2d 数组,我正在尝试找到所有“X”的位置。

我想输出为:在 (A,6), (B,3), (D,5) 中找到

Basically I want to look at the position in where all my "X" are.

您可以使用 np.where 获取每个轴的索引,然后压缩它们以获得所有位置的索引元组:

>>> list(zip(*np.where(Arr == "X")))
[(3, 2), (5, 4), (6, 1)]

如果你想要(行,列)“位置”,你可以这样做:

>>> [(Arr[row, 0], Arr[0, col]) for row, col in zip(*np.where(Arr == "X"))]
[('3', 'B'), ('5', 'D'), ('6', 'A')]

但是,您似乎将数组视为 table。您应该考虑使用 Pandas:

>>> df = pd.DataFrame(Arr[1:, 1:], columns=Arr[0, 1:], index=range(1, len(Arr[1:]) + 1))

>>> df
   A  B  C  D  E  F
1  0  0  0  0  0  0
2  0  0  0  0  0  0
3  0  X  0  0  0  0
4  0  0  0  0  0  0
5  0  0  0  X  0  0
6  X  0  0  0  0  0
7  0  0  0  0  0  0
8  0  0  0  0  0  0

>>> rows, cols = np.where(df == "X")

>>> [*zip(df.index[rows], df.columns[cols])]
[(3, 'B'), (5, 'D'), (6, 'A')]