至少有两种方法可以实现您的目标。在示例A中,运行快速查询以确定您的成员是否是散列的一部分。只要找到匹配,它就会停止。另一方面,示例B可能被证明是更有用的,因为返回所有匹配的值。这使您可以处理与您的成员相关的散列部分,而无需运行其他查询。
#! /usr/bin/env python3
def main():
"""Demonstrate the usage of dict_contains and dict_search."""
my_list = ['ist', 'out', 'ear', 'loopy']
my_hash = {'a': 50, 'across': 14, 'ahash': 12, 'alist': 31, 'an': 73,
'and': 11, 'are': 2, 'as': 34, 'avoid': 82, 'be': 3,
'besides': 49, 'but': 45, 'can': 32, 'check': 51, 'come': 84,
'comparison': 40, 'custom': 61, 'dictionary': 58,
'different': 76, 'difficult': 85, 'do': 86, 'does': 13,
'entire': 37, 'every': 33, 'filled': 77, 'foobarbazz': 20,
'for': 42, 'fuzzy': 53, 'have': 30, 'how': 36, 'however': 68,
'i': 74, 'if': 43, 'implement': 62, 'in': 57, 'information': 46,
'is': 71, 'it': 83, 'like': 64, 'list': 55, 'looping': 70,
'makes': 63, 'match': 16, 'matches': 1, 'member': 29,
'members': 78, 'method': 7, 'might': 6, 'most': 28, 'my': 38,
'name': 18, 'naming': 41, 'of': 52, 'on': 17, 'oop': 35,
'operator': 21, 'over': 19, 'overload': 27, 'own': 72,
'reasons': 79, 'redefine': 10, 'research': 22, 'same': 48,
'search': 75, 'see': 5, 'situation': 39, 'so': 87, 'sounds': 24,
'straightforward': 69, 'stuff': 15, 'such': 66, 'that': 47,
'the': 56, 'then': 54, 'things': 81, 'think': 67, 'this': 59,
'to': 9, 'very': 0, 'want': 23, 'way': 60, 'what': 44,
'whole': 26, 'with': 8, 'without': 65, 'works': 4, 'would': 25,
'yet': 80}
# Example A
for member in my_list:
if dict_contains(my_hash, member):
print('Found:', member)
# Example B
for member in my_list:
match = dict_search(my_hash, member)
if match:
print('Query with', member, 'resulted in', match)
else:
print('Searching with', member, 'failed miserably')
def dict_contains(self, needle):
"""Check if search term can be found in any key of the given dict."""
return any(needle in haystack for haystack in self)
def dict_search(self, pattern):
"""Return the dict's subset where the search term is found in the key."""
return {key: value for key, value in self.items() if pattern in key}
if __name__ == '__main__':
main()
'ahash = hash()'是一个不正确的语法! 'hash()'函数不会创建一个字典,它将返回它的输入参数的散列值(如果它是可散列的)。 – Kasramvd
我想你明白我的意思了。 – baordog
因为你要回到O(n)搜索解决方案(远离散列表),你正在以这种方式损失很多字典的效率。如果某些内容与多个键匹配会怎样返回列表?第一? –