将列表与字典(包含通配符)进行比较,return 个值
Compare list with dictionary (that contains wildcards), return values
我有一个包含多个字符串的列表和一个以字符串(包含通配符)作为键、以整数作为值的字典。
例如像这样:
list1 = ['i', 'like', 'tomatoes']
dict1 = {'tomato*':'3', 'shirt*':'7', 'snowboard*':'1'}
我想遍历 list1,看看 dict1 中是否有一个键(使用通配符)与 list1 中的字符串匹配,并从 dict1 中获取相应的值。所以在这种情况下 3
for 'tomato*'
.
有没有一种方法可以遍历 list1
,看看 dict1 键之一(带通配符)是否与这个特定字符串和 return 来自 dict1
的值相匹配?
我知道我可以遍历 dict1
并以这种方式将键与 list1
中的元素进行比较。但就我而言,字典非常大,此外,我还有很多列表要处理。所以每次循环遍历字典会花费太多时间。
我考虑过将键也变成一个列表,并通过列表理解和 fnmatch()
获得通配符匹配,但是 returned 匹配将无法在字典中找到值(因为通配符)。
这是一个使用默认 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
我有一个包含多个字符串的列表和一个以字符串(包含通配符)作为键、以整数作为值的字典。
例如像这样:
list1 = ['i', 'like', 'tomatoes']
dict1 = {'tomato*':'3', 'shirt*':'7', 'snowboard*':'1'}
我想遍历 list1,看看 dict1 中是否有一个键(使用通配符)与 list1 中的字符串匹配,并从 dict1 中获取相应的值。所以在这种情况下 3
for 'tomato*'
.
有没有一种方法可以遍历 list1
,看看 dict1 键之一(带通配符)是否与这个特定字符串和 return 来自 dict1
的值相匹配?
我知道我可以遍历 dict1
并以这种方式将键与 list1
中的元素进行比较。但就我而言,字典非常大,此外,我还有很多列表要处理。所以每次循环遍历字典会花费太多时间。
我考虑过将键也变成一个列表,并通过列表理解和 fnmatch()
获得通配符匹配,但是 returned 匹配将无法在字典中找到值(因为通配符)。
这是一个使用默认 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