将列表和字典(包含通配符)进行比较,返回值



我有一个包含多个字符串的列表和一个以字符串(包含通配符(为键、以整数为值的字典。

例如:

list1 = ['i', 'like', 'tomatoes']
dict1 = {'tomato*':'3', 'shirt*':'7', 'snowboard*':'1'}

我想浏览list1,看看dict1中是否有一个键(带通配符(与list1中的字符串匹配,并从dict1中获得相应的值。因此,在这种情况下,3用于'tomato*'

有没有一种方法可以迭代list1,看看dict1键中的一个(带通配符(是否与这个特定字符串匹配,并从dict1返回值?

我知道我可以通过这种方式在dict1上迭代,并将键与list1中的元素进行比较。但就我而言,dict非常大,此外,我还有很多列表要查看。因此,每次循环浏览字典都会花费太多时间。我也想过把键变成一个列表,并通过列表理解和fnmatch()获得通配符匹配,但返回的匹配无法在dict中找到值(因为通配符(。

这里有一个使用默认python包实现的数据结构来帮助您。

from collections import defaultdict

class Trie(defaultdict):
def __init__(self, value=None):
super().__init__(lambda: Trie(value))  # Trie is essentially hash-table within hash-table
self.__value = value
def __getitem__(self, key):
node = self
if len(key) > 1:  # allows you to access the trie like this trie["abc"] instead of trie["a"]["b"]["c"]
for char in key:
node = node[char]
return node
else:  # actual getitem routine
return defaultdict.__getitem__(self, key)
def __setitem__(self, key, value):
node = self
if len(key) > 1:  # allows you to access the trie like this trie["abc"] instead of trie["a"]["b"]["c"]
for char in key[:-1]:
node = node[char]
node[key[-1]] = value
else:  # actual setitem routine
if type(value) is int:
value = Trie(int(value))
defaultdict.__setitem__(self, key, value)
def __str__(self):
return str(self.__value)

d = Trie()
d["ab"] = 3
print(d["abcde"])
3

最新更新