以下是一个示例代码,用于按照单词的匹配数量对字符串列表进行排序:
def sort_by_word_count(word_list, search_word):
word_count = {}
for word in word_list:
count = word.count(search_word)
if count > 0:
word_count[word] = count
sorted_words = sorted(word_count.items(), key=lambda x: x[1], reverse=True)
sorted_list = [word[0] for word in sorted_words]
return sorted_list
# 示例用法
words = ['apple', 'banana', 'orange', 'pineapple', 'grapefruit']
search_word = 'apple'
sorted_words = sort_by_word_count(words, search_word)
print(sorted_words)
这段代码首先定义了一个sort_by_word_count
函数,它接受一个字符串列表word_list
和一个搜索词search_word
作为参数。然后,它遍历word_list
中的每个单词,并使用count
函数获取每个单词中搜索词的出现次数。如果搜索词在单词中出现至少一次,它会将单词和匹配次数添加到word_count
字典中。
接下来,它使用sorted
函数对word_count
字典按照匹配次数进行排序,使用lambda
函数作为排序的关键字。排序完成后,它将排序后的单词提取出来,并返回一个新的列表sorted_list
。
在示例中,我们定义了一个字符串列表words
和一个搜索词search_word
,然后调用sort_by_word_count
函数进行排序,并打印排序后的结果。输出结果为['apple', 'pineapple', 'banana', 'orange', 'grapefruit']
,按照匹配次数从高到低进行了排序。
上一篇:按品牌获取CSS
下一篇:按匹配的键/值对重新组织对象数组