【问题标题】:Python: Testing if a value is present in a defaultdict listPython:测试一个值是否存在于 defaultdict 列表中
【发布时间】:2011-04-09 16:56:44
【问题描述】:

我想测试一个字符串是否存在于 defaultdict 的任何列表值中。

例如:

from collections import defaultdict  
animals = defaultdict(list)  
animals['farm']=['cow', 'pig', 'chicken']  
animals['house']=['cat', 'rat']

我想知道“牛”是否出现在动物的任何列表中。

'cow' in animals.values()  #returns False

我想要在这种情况下返回“True”的东西。是否有相当于:

'cow' in animals.values()  

对于默认字典?

谢谢!

【问题讨论】:

  • 不要让defaultdict 迷惑你。如果你有一个普通的dict,你仍然会遇到同样的问题。 animals.values() 是列表列表,而不是字符串列表。
  • 是的,确实如此。感谢您的帮助。

标签: python list collections dictionary


【解决方案1】:

此示例将展平列表,检查每个元素并返回 True 或 False,如下所示:

>>> from collections import defaultdict  
>>> animals = defaultdict(list)  
>>> animals['farm']=['cow', 'pig', 'chicken']  
>>> animals['house']=['cat', 'rat']

>>> 'cow' in [x for y in animals.values() for x in y]
True

【讨论】:

    【解决方案2】:
    any("cow" in lst for lst in animals.itervalues())
    

    【讨论】:

      【解决方案3】:

      在这种情况下,defaultdict 与常规 dict 没有什么不同。您需要遍历字典中的值:

      any('cow' in v for v in animals.values())
      

      或者更程序化:

      def in_values(s, d):
          """Does `s` appear in any of the values in `d`?"""
          for v in d.values():
              if s in v:
                  return True
          return False
      
      in_values('cow', animals)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多