以下是一个示例代码,演示如何按照单词开头筛选结果:
def filter_words_starting_with(words, prefix):
filtered_words = []
for word in words:
if word.startswith(prefix):
filtered_words.append(word)
return filtered_words
words = ['apple', 'banana', 'orange', 'pear', 'grape']
prefix = 'a'
filtered_words = filter_words_starting_with(words, prefix)
print(filtered_words)
这个示例中,我们定义了一个名为filter_words_starting_with
的函数,它接受一个单词列表和一个前缀作为参数。函数内部使用一个循环遍历列表中的每个单词,然后使用startswith()
方法来判断单词是否以指定的前缀开头。如果是,就将该单词添加到filtered_words
列表中。最后,函数返回筛选后的单词列表。
在示例中,我们创建了一个名为words
的单词列表和一个前缀'a'
。然后,我们调用filter_words_starting_with
函数,并将words
和prefix
作为参数传递进去。函数返回筛选后的单词列表,我们将其打印出来。
输出结果为:['apple']
,因为只有单词'apple'
以字母'a'
开头。