在矩阵中查找单词 [英] Finding word in a matrix

查看:215
本文介绍了在矩阵中查找单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个矩阵文件(python读取的内容像一个列表列表),我需要确定在给定方向上是否有另一个文件中的单词出现在该矩阵中. 例如:给定此矩阵:

I have a matrix file (which python reads like a list of lists) and I need to tell if a word from a different file appears in that matrix, in a given direction. for example: given this matrix:

c,a,T,e
o,a,t,s
w,o,t,e
n,o,l,e

单词:

caT, cow, own, cat

和说明:

downright (diagonal)

我希望输出:

cat:1

并指明方向:

down, right

我希望:

cow:1
own:1
cat:1

我的功能设置如下:

def word_finder(word_list,matrix, directions):

我发现很难做的是浏览列表列表,然后遍历水平索引(例如对角线:( 寻求帮助

推荐答案

尝试一下:

from itertools import chain
from collections import defaultdict

matrix= [['c', 'a', 'T', 'e'],
         ['o', 'a', 't', 's'],
         ['w', 'o', 't', 'e'],
         ['n', 'o', 'l', 'e']]
words = ['caT', 'cow', 'own', 'cat']

d = defaultdict(int)
for i in chain(matrix, list(zip(*matrix))): # list(zip(*matrix)) is for down direction
    for word in words:
        if word in ''.join(i):
            d[word] = d[word] + 1

d将是您的预期输出. {'caT': 1, 'cow': 1, 'own': 1}

The d will be your expected output. {'caT': 1, 'cow': 1, 'own': 1}

这篇关于在矩阵中查找单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆