如何判断嵌套字典指定字段的所有字符串均含目标单词(不区分大小写)
判断列表中所有字符串是否均包含指定单词(不区分大小写)
问题背景
给定如下嵌套字典及生成列表的代码:
Data={ 0:{ 'country1': "Ryan lives in America", 'country_one': "5", 'med_dict':{ 0: { 'endDate': "732", 'endTime': "89", } }, }, 1: { 'country1': "Sam lives in america", 'country_three': "90", 'med_dict': { 0: { 'endDate': "245", 'endTime': "222", } }, } } res = [v1['country1'] for k1, v1 in Data.items()] print(res) # 输出: ['Ryan lives in America', 'Sam lives in america']
需要判断res列表中的所有字符串是否均包含不区分大小写的"America"(即"America"或"america"均可),满足则返回True,否则返回False。
实现方法
方法一:使用all()结合大小写转换
通过将字符串统一转为小写(或大写),再检查目标单词是否存在,实现不区分大小写的匹配:
# 基于已生成的res列表 all_contains = all("america" in s.lower() for s in res) print(all_contains) # 示例中输出True
- 逻辑:
all()函数会验证迭代器内所有元素是否为True,只要有一个元素不满足条件就返回False;s.lower()将字符串转为小写,确保匹配不受大小写影响。
方法二:使用正则表达式实现精确单词匹配
如果需要严格匹配独立单词(避免匹配类似"American"这类包含目标字符串但并非独立单词的情况),可以用正则表达式:
import re # 编译正则模式:\b表示单词边界,re.IGNORECASE开启大小写不敏感 pattern = re.compile(r'\bamerica\b', re.IGNORECASE) all_contains = all(pattern.search(s) for s in res) print(all_contains) # 示例中输出True
- 逻辑:
re.compile()预编译正则模式提升效率,pattern.search(s)检查字符串中是否存在匹配的独立单词,re.IGNORECASE忽略大小写差异。
测试场景示例
若将res中的某元素改为"Sam lives in Canada",上述两种方法都会返回False,因为该字符串不包含目标单词。
内容的提问来源于stack exchange,提问作者Trishna
相关产品推荐
相关产品推荐

