字典键中的通配符 [英] Wildcard in dictionary key
本文介绍了字典键中的通配符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一本字典:
rank_dict = {'V*': 1, 'A*': 2, 'V': 3,'A': 4}
如您所见,我在一个V的末尾添加了一个*.而3可能只是V的值,我想要另一个V1,V2,V2234432等键...我想检查一下反对:
As you can see, I have added a * to the end of one V. Whereas a 3 may be the value for just V, I want another key for V1, V2, V2234432, etc...I want to check it against:
checker = 'V30'
并获取值.正确的语法是什么?
and get the value. what is the correct syntax for this?
for k, v in rank_dict.items():
if checker == k:
print(v)
推荐答案
You can use fnmatch.fnmatch
to match Unix shell-style wildcards:
>>> import fnmatch
>>> fnmatch.fnmatch('V34', 'V*')
True
>>> rank_dict = {'V*': 1, 'A*': 2, 'V': 3,'A': 4}
>>> checker = 'V30'
>>> for k, v in rank_dict.items():
... if fnmatch.fnmatch(checker, k):
... print(v)
...
1
注意:每次查找的时间复杂度为O(n).对于大型词典,这可能会成为一个问题.仅当查询性能不成问题时才建议使用.
NOTE: Every lookup will have O(n) time complexity. This may become an issue with large dictionaries. Recommended only if lookup performance is not an issue.
这篇关于字典键中的通配符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文