我有点晚了,但另一种方法是使用列表理解和any
函数,它接受一个可迭代并True
在一个元素为时返回True
:
# Checking if string 'Mary' exists in the lists of the dictionary values
print any(any('Mary' in s for s in subList) for subList in myDict.values())
如果您想计算其中包含“玛丽”的元素数量,您可以使用sum()
:
# Number of sublists containing 'Mary'
print sum(any('Mary' in s for s in subList) for subList in myDict.values())
# Number of strings containing 'Mary'
print sum(sum('Mary' in s for s in subList) for subList in myDict.values())
通过这些方法,我们可以轻松地创建函数来检查哪些键或值匹配。
要获取包含“Mary”的密钥:
def matchingKeys(dictionary, searchString):
return [key for key,val in dictionary.items() if any(searchString in s for s in val)]
要获取子列表:
def matchingValues(dictionary, searchString):
return [val for val in dictionary.values() if any(searchString in s for s in val)]
要获取字符串:
def matchingValues(dictionary, searchString):
return [s for s i for val in dictionary.values() if any(searchString in s for s in val)]
要同时获得:
def matchingElements(dictionary, searchString):
return {key:val for key,val in dictionary.items() if any(searchString in s for s in val)}
如果你只想得到包含“Mary”的字符串,你可以做一个双重列表理解:
def matchingStrings(dictionary, searchString):
return [s for val in dictionary.values() for s in val if searchString in s]