如何获取行和列中的字符?

2024-04-26 21:35:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图提取一个二维数组中的单词,所以我需要做一个行和列检查,这样我就可以得到字符。你知道吗

示例: 我有一个数组,它包含一个二维空间,如图Click here所示,这是存储数组的代码。我已经把它调整到15x15了

arr2 = np.array([my_list2])
arr2 = arr2.reshape(15,15)

问题是每次我提取字符时,它都不会给我苹果的a。 E A G L E P P L E

这是让我提取字符串的代码: board_size = 15 print(arr2)

for i in range(board_size):
    for j in range(board_size):
        val = arr2[i,j]
        if val != '0' :
        print(val)

你知道吗` 我需要的输出是能够显示鹰和苹果。你知道吗


Tags: 代码in苹果board示例forsizerange
2条回答

在这种情况下,您可以遍历行和列(使用索引)并使用列表理解来删除0

a = np.array([['T','E','S','T'],
['0','0','0','E'],
['0','0','0','S'],
['0','0','0','T']])
height,width = a.shape
for i in range(height):
    word = ''.join([j for j in a[i] if j!='0'])
    if len(word)>=2: print(word)
for i in range(width):
    word = ''.join([j for j in a[:,i] if j!='0'])
    if len(word)>=2: print(word)

输出:

TEST
TEST

a是硬编码的值,例如清晰度,请注意a.shape的用法,它比幻数更优雅。你知道吗

正如在注释中所指出的,它在原始形式中有一个缺陷,为了避免这个问题,for应该按照以下方式:

for i in range(height)
    words = ''.join(a[i]).split('0')
    words = [i for i in words if len(i)>=2]
    if words: print(words)
for i in range(width):
    words = ''.join(a[:,i]).split('0')
    words = [i for i in words if len(i)>=2]
    if words: print(words)

注意,现在words是list,这个方法还可以在一行或一列中检测两个或多个单词。你知道吗

这是一种不用numpy就能实现目标的方法:

def print_non_0_len_ge_1(li):
    """removes 0 from front/back of line, prints rest of line if > 1 consecutive letter
    splitting at 0 between words."""
    for line in li:
        no_zero = ''.join(line).strip("0").split("0")
        for p in no_zero:
            if len(p)>1:
                print(*p,sep="\n")
                print("")   

data = [['0', '0', '0', '0', '0', '0', '0', '0', '0', '0'], 
        ['0', '0', '0', 'E', 'A', 'G', 'L', 'E', '0', '0'], 
        ['0', '0', '0', '0', 'P', '0', '0', '0', '0', '0'], 
        ['0', '0', '0', '0', 'P', '0', 'P', '0', '0', '0'],
        ['0', '0', '0', '0', 'L', '0', 'I', '0', '0', '0'], 
        ['0', '0', '0', 'C', 'E', 'R', 'E', 'A', 'L', '0'],
        ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0']]

# apply to lines
print_non_0_len_ge_1(data)

# apply to transposed data to get the columns
print_non_0_len_ge_1(zip(*data))  

输出:

E
A
G
L
E

C
E
R
E
A
L

A
P
P
L
E

P
I
E

如果使用numpy,您可以类似地解决这个问题—只需删除起始/结束0,在0处拆分并应用于普通和转置的数据。你知道吗

该方法有一个缺点-您需要在两个方向上的任何非构词字符之间0才能让它工作(您不能使用“EGG”开头的ad“(E)agle”,因为您从它得到GP两次。你知道吗

相关问题 更多 >