该单词的行索引和列索引的交叉写功能命名find_word_horizontal接受字符的 2维列表(如填字游戏)和一个 字符串(单词)作为输入参数。该函数搜索 第2d列表的行以找到匹配的单词。如果找到匹配项,则此函数将返回一个包含匹配起始点的行索引和列索引的列表,否则返回值None(无 报价单)。的Python:查找在2D列表中的单词并返回是在列表
注意:我很抱歉发布一个很长的帖子在这里。我很抱歉,但没有发布适当的问题,我不可能寻求帮助。
For example if the function is called as shown below:
>
> crosswords=[['s','d','o','g'],['c','u','c','m'],['a','c','a','t'],['t','e','t','k']]
> word='cat'
>
> find_word_horizontal(crosswords,word)
>
> then your function should return [2,1]
>
> Notice that the 2d input list represents a 2d crossword and the
> starting index of the horizontal word 'cat' is [2,1]
Note: In case of multiple matches only return the match with lower row index. If you find two matches in the same row
then return the match with lower column index
我写了这段代码。也许这可能不是最好的代码,但是:
def find_word_horizontal (crosswords, word):
list = []
output_list = []
row_index = -1
column_index = 0
list = word.split()
for sublist in crosswords:
if (sublist[1:] == list[:] or sublist[0:-1] == list[:]):
column_index += 1
row_index += 1
output_list.append(row_index)
output_list.append(column_index)
return (output_list)
#Main Program
crosswords = [['s','d','o','g'],['c','u','c','m'],['a','c','a','t'],['t','e','t','k']]
word = 'cat'
result = find_word_horizontal(crosswords,word)
print (result)
什么我在这里做的是首先把这个词(即“猫”)到一个列表。第二,我已将sublist
(即2d列表中的列表)切片以检查三个字母的单词“cat
”。我知道我有这种硬编码,但我找不到任何其他方式。上面,这个问题要求以这种方式。
这是我得到的输出:
[3, 0]
为什么不是if语句更新Column_Index中的价值?切片顺序或什么有问题?任何帮助,将不胜感激。
一个单词可以跨越多行,所以前三个字母在一个列表中,最后两个在下一个?如果不是的话,一个简单的方法可能是将每一行连接在一起并搜索整个字符串,而不是逐字比较字符。如果你认为这会起作用,我可以在以后写一个答案。 –
当然>感谢您的帮助。 –
试试吧,让我知道如果作品如何! –