Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

python - How to get the characters in row and column?

I'm trying to extract the words in a 2d array so I need to do a row and column inspection so that I could get the characters.

Example: I have an array that contains a 2d dimensional which is shown in this photo Click here and this is the code that stores the array. I already resize it into 15x15

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

The problem is every time I extracted the characters it won't give me the a for the apple. E A G L E P P L E

This is the code that let me extract the strings: 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)

` The output I need is to be able to display eagle and apple.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a way to achieve what you want to do without 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="
")
                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))  

Output:

E
A
G
L
E

C
E
R
E
A
L

A
P
P
L
E

P
I
E

You can solve it similarily if using numpy - just remove the starting / ending 0, split at 0 and apply to normal and transposed data.

The method has a drawback - you need 0 between any non-word-forming characters in both directions to allow it to work (you can not use "EGG" starting ad "(E)agle" because you get GP twice from it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...