![](/img/trans.png)
[英]Check if all letters of string are contained in list of letters in Python
[英]Check if a string is in a list of letters - Python3
我有一個包含字母的列表,我需要檢查位於另一個列表中的預定單詞是否水平位於該字母列表內。
即:
mat_input = [['v', 'e', 'd', 'j', 'n', 'a', 'e', 'o'], ['i', 'p', 'y', 't', 'h', 'o', 'n', 'u'], ['s', 'u', 'e', 'w', 'e', 't', 'a', 'e']]
words_to_search = ['python', 'fox']
我不需要告訴您是否找不到一個單詞,但是如果是的話,我需要告訴您哪個單詞。
我的問題是,到目前為止,我已經嘗試過像這樣的循環逐個字母地進行比較:
for i in range(n): # n = number of words
for j in range(len(word_to_search[i])): # size of the word I'm searching
for k in range(h): # h = height of crossword
for m in range(l): # l = lenght of crossword
但這不起作用,在上一個循環中,我嘗試了幾種if / else條件來判斷是否找到了整個單詞。 我該如何解決?
您可以使用str.join
:
mat_input = [['v', 'e', 'd', 'j', 'n', 'a', 'e', 'o'], ['i', 'p', 'y', 't', 'h', 'o', 'n', 'u'], ['s', 'u', 'e', 'w', 'e', 't', 'a', 'e']]
words_to_search = ['python', 'fox']
joined_input = list(map(''.join, mat_input))
results = {i:any(i in b or i in b[::-1] for b in joined_input) for i in words_to_search}
輸出:
{'python': True, 'fox': False}
首先,將mat_input
每個子列表加入一個字符串中:
mat_input_joined = [''.join(x) for x in mat_input]
然后循環搜索您的單詞以進行搜索,只需使用in
運算符即可查看每個字符串中是否包含該單詞:
for word_to_search in words_to_search:
result = [word_to_search in x for x in mat_input_joined]
print('Word:',word_to_search,'found in indices:',[i for i, x in enumerate(result) if x])
結果:
Word: python found in indices: [1]
Word: fox found in indices: []
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.