【问题标题】:check substring exists in a dictionary value during iteration检查迭代期间字典值中是否存在子字符串
【发布时间】:2021-03-16 03:55:39
【问题描述】:

以下代码运行良好,但任何人都可以指导如何简化它。 newrelicid 是一个字典,其中包含“数字”作为键和“某些字符串”作为值(字符串可以包含子字符串,如 prod、test、local 等 ) 基本上我试图忽略包含来自列表['dev','staging','qat','uat','local','eu']的子字符串的值( j )@

样本newrelicid值

{1: 'Service PROD', 2: 'service', 3: 'guess-service (Production)', 4: 'check-service (Dev)', 5: 'analytics-service (Staging)' }

循环:

for i,j in newrelicid.items():
  if 'staging' not in j.lower() and not 'qat' in j.lower() and not 'uat' in j.lower() and not 'local' in j.lower() and not 'eu' in j.lower() and not 'dev' in j.lower():
    print(j)    

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    您可以使用any() 有效地模拟嵌套迭代:

    >>> newrelicid = {
    ...     1: 'Service PROD',
    ...     2: 'service',
    ...     3: 'guess-service (Production)',
    ...     4: 'check-service (Dev)',
    ...     5: 'analytics-service (Staging)'
    ... }
    >>> blacklist = {'dev','staging','qat','uat','local','eu'}
    
    >>> {v for v in newrelicid.values()
    ...     if not any(i in v.casefold() for i in blacklist)}
    {'Service PROD', 'guess-service (Production)', 'service'}
    

    这会产生一个set[str] 的传递值。

    【讨论】:

      【解决方案2】:

      你可以使用正则表达式:

      import re
      
      pattern = r'staging|local|uat|qat|dev|eu' # one pattern for all keywords
      
      newrelicid = {1: 'Service PROD', 2: 'service', 3: 'guess-service (Production)',
                    4: 'check-service (Dev)', 5: 'analytics-service (Staging)' }
      
      for j in newrelicid.values():
          if re.search(pattern,j.lower()): # match with lowercase
              print(j)
      
      check-service (Dev)
      analytics-service (Staging)
      

      如果你需要的是整个单词而不仅仅是子字符串,你可以改进模式:

      pattern = r'\b(staging|local|uat|qat|dev|eu)\b'
      

      【讨论】:

        【解决方案3】:

        您似乎想应用过滤器。

        顺便说一句,由于您只查看字典中的字符串,请使用 dict.values()

        l = ['staging','qat', 'uat', 'local', 'eu', 'dev']
        
        list(filter(lambda x : not any(e in x.lower() for e in l),  newrelicid.values()))
        
        ['Service PROD', 'service', 'guess-service (Production)']
        

        【讨论】:

        • 谢谢 Marco,无论如何我可以在您分享的行中添加一个条件if 'worker' in
        • 我不确定我是否理解这一点,你能解释得更好吗?条件是什么?
        • {v for v in newrelicid.values() if not any(i in v.casefold() for i in blacklist) and 'worker' in v } 我已经添加了一个条件worker in v 和布拉德所罗门的答案,同样我正在寻找如何从你的脚本中实现
        • 确保您可以根据需要向 lambda 函数添​​加任意数量的条件。 filter 的思想是,如果 lambda 函数中 : 之后的表达式计算结果为 True,则该元素保留在输出列表中
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-03-04
        • 2021-10-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-09
        • 2011-07-30
        相关资源
        最近更新 更多