Python - 字典中的前缀键匹配

pythonserver side programmingprogramming更新于 2025/2/26 21:00:17

简介

Python 是一种灵活的编程语言,以其简单性和一致性而闻名。其强大的功能之一是能够在字典中执行前缀键匹配。此功能允许快速查找以特定前缀开头的键。在本文中,我们将探讨在 Python 中实现前缀键匹配的三种方法,以及它们的比较算法、分步说明、Python 语法和代码示例。通过利用这些技术,我们将大大提高我们有效管理和提取数据的能力。让我们进入前缀键匹配的世界吧!

方法 1:线性搜索

算法

直接搜索方法是在字典中执行前缀键匹配的直接方法。它包括遍历所有键并检查每个键是否以所需的前缀开头。以下是此方法的算法描述和分步说明 -

  • 步骤 1 - 定义函数 prefix_match_linear() 并初始化一个空列表来存储协调键

  • Step 2 - Repeat through each key within the lexicon

  • Step 3 - Check if the key begins with the specified prefix.

  • Step 4 - On the off chance that the prefix coordinate is found, add the key to the list.

  • Step 5 - Rehash steps 3-4 for all keys

  • Step 6 - Return the list of coordinating keys.

示例

def prefix_match_linear(dictionary, prefix):
    matches = []
    for key in dictionary.keys():
        if key.startswith(prefix):
            matches.append(key)
    return matches


fruit_dict = {
    'apple': 1,
    'apricot': 2,
    'banana': 3,
    'orange': 4,
    'pineapple': 5
}

prefix = 'app'
matches = prefix_match_linear(fruit_dict, prefix)
print(matches)

输出

['apple']

方法 2:Trie 数据结构

Trie 信息结构可能是一种树状结构,在高效前缀匹配方面超出预期。让我们研究如何利用 Trie 信息结构执行前缀键协调 −

算法

  • Step 1 - Define a dictionary that contains multiple elements.

  • Step 2 - Create two classes separately named TrieNode and Trie. Create the non-parameterized constructor in the TrieNode and set their attribute with certain values.

  • Step 3 - Similarly, define the constructor in Trie class and create the user-defined function insert inside the Trie class, and use for loop to iterate through each key within the word reference

  • Step 4 - Embed each key into the Trie

  • Step 5 - Hunt for the specified prefix within the Trie.

  • Step 6 - Recover all the keys that coordinate the prefix

示例

fruit_dict = {
    'apple': 1,
    'apricot': 2,
    'banana': 3,
    'orange': 4,
    'pineapple': 5
}

class TrieNode:
    def __init__(self):
        self.children = {}
        self.is_end_of_word = False


class Trie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        node = self.root
        for char in word:
            if char not in node.children:
                node.children[char] = TrieNode()
            node = node.children[char]
        node.is_end_of_word = True

    def get_matches(self, prefix):
        node = self.root
        matches = []
        for char in prefix:
            if char not in node.children:
                return matches
            node = node.children[char]
        self._collect_matches(node, prefix, matches)
        return matches

    def _collect_matches(self, node, prefix, matches):
        if node.is_end_of_word:
            matches.append(prefix)
        for char, child in node.children.items():
            self._collect_matches(child, prefix + char, matches)


def prefix_match_trie(dictionary, prefix):
    trie = Trie()
    for key in dictionary.keys():
        trie.insert(key)
    return trie.get_matches(prefix)


prefix = 'ban'
matches = prefix_match_trie(fruit_dict, prefix)
print(matches)

输出

['banana']

方法 3:使用 Python 的内置过滤函数

Python 提供了一个内置的 filter() 函数,允许我们编写一个有效的单行代码来执行前缀键匹配。通过将这项工作应用于词典键和 lambda 工作,我们将完成简短明了的代码。它的工作原理如下 -

算法

  • Step 1 - Create a dictionary named fruit_dict.

  • Step 2 - Define a function prefix_match_filter() that contains two arguments in the function definition and then make a lambda work that checks on the off chance that each key begins with the required prefix.

  • Step 3 - Apply the filter() function to the word reference keys, utilizing the lambda work as the channel condition.

  • Step 4 - Collect the resultant keys in a list.

  • Step 5 - Invoke the function and pass its value to the variable named matches.

  • Step 6 - Finally, print the value of the matches.

示例

fruit_dict = {
    'apple': 1,
    'apricot': 2,
    'banana': 3,
    'orange': 4,
    'pineapple': 5
}

def prefix_match_filter(dictionary, prefix):
    matches = list(filter(lambda key: key.startswith(prefix), dictionary.keys()))
    return matches

prefix = 'or'
matches = prefix_match_filter(fruit_dict, prefix)
print(matches)

输出

['orange']

结论

在本文中,我们研究了三种在 Python 词典中执行前缀键匹配的方法。我们选择了直接搜索方法,这种方法简单但对于较大的数据集效率较低。然后,我们深入研究了 Trie 数据结构,它在前缀匹配方面表现出色,并且在效率方面取得了进步。每种方法都有自己的优点,可以根据手头任务的要求进行选择。通过在 Python 中掌握前缀键匹配技术,开发人员可以有效地从词典中恢复数据并简化他们的数据管理任务。


相关文章


有用资源