简体   繁体   English

在列表列表中查找单词

[英]find words in a list of lists

I need to find words in a list of lists (a somewhat matrix), by entering a given direction to search. 我需要通过输入给定的搜索方向,在列表列表(有点矩阵)中找到单词。 so for example, if I need to search all words that are horizontal from right to left - I will do that by manipulating the indexes that run over the columns. 因此,例如,如果我需要搜索从右到左水平的所有单词-我将通过处理在列上运行的索引来做到这一点。

the_matrix = [['a', 'p', 'p', 'l', 'e'],
              ['a', 'g', 'o', 'd', 'o'],
              ['n', 'n', 'e', 'r', 't'],
              ['g', 'a', 'T', 'A', 'C'],
              ['m', 'i', 'c', 's', 'r'], 
              ['P', 'o', 'P', 'o', 'P']]
the_word_list = ['ert','PoP']

def find_words_in_matrix(directions):
    good_list = []
    for col in range(len(the_matrix[0])):
        for row in range(len(the_matrix)):
            for word in the_word_list:
                for i in range(len(word)):
                    found_word = True
                    #a = word[i]
                    if col + i > len(the_matrix[0])-1:
                        break
                    #b = the_matrix[row][col+i]
                    if word[i] != the_matrix[row][col+i]:
                        found_word=False
                        break
                if found_word is True:
                    good_list.append(word)

    return good_list

Im getting the output: 我正在获取输出:

['PoP', 'ert', 'PoP', 'ert', 'PoP']

instead of: 代替:

['PoP', 'ert', 'PoP']

*pop shows up twich at the bottom line, not three times. * pop在最后一行显示,而不是三次。 and ert only once. 只能说一次。 that is my problem 那是我的问题

thanks for the help! 谢谢您的帮助!

You are getting stray matches when the break terminates the loop early before the whole word has matched. break在整个单词匹配之前提前终止循环时,您将获得零散匹配。 To eliminate this, you can keep track of the match length: 为了消除这种情况,您可以跟踪匹配长度:

def find_words_in_matrix(directions):
    good_list = []
    for col in range(len(the_matrix[0])):
        for row in range(len(the_matrix)):
            for word in the_word_list:
                match_len = 0
                for i in range(len(word)):
                    found_word = True
                    #a = word[i]
                    if col + i > len(the_matrix[0])-1:
                        break
                    #b = the_matrix[row][col+i]
                    if word[i] != the_matrix[row][col+i]:
                        found_word=False
                        break
                    match_len += 1
                if (match_len == len(word)) and (found_word is True):
                    good_list.append(word)

    return good_list

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM