Finding a word from a list of strings

2019-07-31 09:05发布

问题:

Say I have a list of strings

["rdfa", "gijn", "ipqd"]

and have a variable containing the string "and", how would I be able to check if "and" is in the list? To make this more clear think of the list as a word search:

rdfa
gijn
ipqd

I see the vertical word "and", but how would I be able to check if the word "and" is in the list? Finding horizontal words was much easier, but finding a vertical word is confusing me. I was thinking possibly that I would need to find if the first letter of "and" is in any element in the list, then I would need to find if the second letter is in the same column as the first, and also in the row above or below the first letter, and the same for subsequent letters (as I'd like this to work for any length word). However I'm not sure how this would be implemented. I hope the question is clear as it's quite difficult to explain without a showing a word search.

回答1:

A pure python way to transpose your matrix of letters would be

def transpose(l):
    return map(''.join, zip(*l))

l = ["rdfa", "gijn", "ipqd"]

if 'and' in transpose(l):
    ...


回答2:

A list element is unaware of the rest of the elements, so you can't compare it vertically. If the word list you have is not huge, the most efficient way is to construct the transpose of your list like:

np.array(your_word_list).T.tolist()

and then look horizontally. If your words are not the same length just pad them with spaces.

If you are trying to solve a word puzzle, then check this question or this module