以下是一个示例代码,用于实现按任意顺序匹配的单词列表,但只有在相邻/最多相隔n个单词时才匹配。
def match_words(word_list, words_to_match, n):
match_indices = []
matched_words = []
# 遍历给定的单词列表
for i, word in enumerate(word_list):
# 如果当前单词与要匹配的单词列表中的第一个单词匹配
if word == words_to_match[0]:
# 将当前单词的索引添加到匹配索引列表中
match_indices.append(i)
matched_words.append(word)
j = 1
# 寻找与后续单词匹配的单词
while j < len(words_to_match):
# 计算当前单词索引与上一个匹配单词索引之间的距离
distance = i - match_indices[-1] - 1
# 如果距离小于等于n,则认为是匹配的单词
if distance <= n and word_list[i + j] == words_to_match[j]:
match_indices.append(i + j)
matched_words.append(word_list[i + j])
else:
# 匹配失败,清除已匹配的单词列表
match_indices = []
matched_words = []
break
j += 1
# 如果已找到完整的匹配单词列表,则返回匹配索引列表
if j == len(words_to_match):
return match_indices, matched_words
# 没有找到匹配的单词列表
return None, None
# 测试示例
word_list = ['apple', 'banana', 'orange', 'kiwi', 'grape', 'watermelon']
words_to_match = ['banana', 'kiwi']
n = 1
indices, words = match_words(word_list, words_to_match, n)
if indices is not None:
print("匹配成功!")
print("匹配的单词索引:", indices)
print("匹配的单词列表:", words)
else:
print("未找到匹配的单词列表")
在上述示例中,match_words
函数接受三个参数:word_list
(给定的单词列表),words_to_match
(要匹配的单词列表)和 n
(相邻/最多相隔的单词数)。
该函数首先创建两个空列表,match_indices
用于存储匹配单词的索引,matched_words
用于存储匹配的单词。
然后,函数遍历给定的单词列表,检查每个单词是否与要匹配的单词列表的第一个单词匹配。如果匹配成功,则将当前单词的索引添加到 match_indices
列表中,并将单词添加到 matched_words
列表中。
接下来,使用一个循环来寻找后续单词的匹配。在循环中,函数首先计算当前单词索引与上一个匹配单词索引之间的距离。如果距离小于等于 n
,则认为是匹配的单词,并将其索引添加到 match_indices
列表中。
如果找到完整的匹配单词列表,则返回匹配索引列表和匹配的单词列表。否则,清除已匹配的单词列表,继续遍历单词列表,直到找到匹配的单词列表或遍历结束。
最后,根据返回值判断是否找到匹配的单词列表,并进行相应的输出。
在示例中,给定的单词列表为 ['apple', 'banana', 'orange', 'kiwi', 'grape', 'watermelon']
,要匹配的单词列表为 `['banana', 'ki
下一篇:按任意索引打印字符串字母