【问题标题】:python: find out if an array of objects meets certain criteriapython:找出一个对象数组是否满足某些条件
【发布时间】:2018-05-05 10:51:56
【问题描述】:

我有一个对象列表,例如

[{'type' :'car', 'color' : 'red', 'engine' : 'diesel'}, {'type' : 'truck'...}

现在我正在寻找基于 python 3 的方法,该方法允许我定义返回 true 或 false 的过滤器。 在那个阵列中是否有一辆红色卡车和一辆装有柴油发动机的汽车? 有人知道从哪里开始寻找吗?

基本上,我想创建一个服务,允许您将规则与此类列表进行匹配。就像用户可以定义一些过滤器一样,我应用于返回 true 或 false 的列表。

比如“color=red and engine=diesel”...就像你可以在 prolog 中做的一样。看了一下pyke,好像太复杂了

【问题讨论】:

  • 您是否尝试过使用 for 循环?为什么这不起作用?
  • 你可以从filter函数开始。
  • 坦率地说,我不明白反对意见。是的,这是一个简单的问题,但并不是特别糟糕。
  • @xaav 我同意,他们什么都没试过,但不值得-5
  • 我认为我的问题并不清楚。我正在寻找类似规则引擎的东西。我知道的那个过滤器的东西。基本上我想创建一个你可以发送规则的服务,如果应用于该数组的规则将返回 true 或 false,它会返回。所以它应该是可定制的

标签: python json filter


【解决方案1】:

给定:

>>> inv=[{'type' :'car', 'color' : 'red', 'engine' : 'diesel'}, {'type' : 'truck','color':'red','engine':'diesel'}, {'type':'bike','color':'red','engine':None}]

由于您有一个字典列表,请构建一个包含您要过滤的内容的字典:

>>> fo={'color':'red', 'type':'car'}

然后使用all 过滤元素之间的andany 过滤or

>>> [d for d in inv if all(d[e]==fo[e] for e in fo if e in d)] 
[{'color': 'red', 'engine': 'diesel', 'type': 'car'}]

如果你更喜欢过滤功能,同样的方法:

>>> fo={'engine': 'diesel'}
>>> filter(lambda d: all(d[e]==fo[e] for e in fo if e in d), inv)
[{'color': 'red', 'engine': 'diesel', 'type': 'car'}, {'color': 'red', 'engine': 'diesel', 'type': 'truck'}]

【讨论】:

    【解决方案2】:

    您可以构建一个列表理解,仅选择符合预期条件的元素:

    my_objects = [{'type' :'car', 'color' : 'red', 'engine' : 'diesel'}]
    
    print([x for x in my_objects if x['type'] == 'car' and x['color'] == 'red'])
    

    【讨论】:

    • 这可能是最好的答案。我想知道性能与我的相比如何。
    • 你为什么不编辑你的问题并准确解释你想要什么。那条评论也不是很清楚。
    • 那个看起来很有前途!
    • 好吧,太快了……那不是我想做的……我想我可能需要使用正则表达式
    【解决方案3】:

    我更喜欢列表理解:

    l = [{'type' :'car', 'color' : 'red', 'engine' : 'diesel'}, {'type' : 'truck'...}
    d = [d for d in l if (key, value) in d.items() and (key, value) in d.items()]
    

    【讨论】:

      【解决方案4】:

      只需使用for-loop 创建一个function

      def check(lst, vehicle, val):
          for d in lst:
              if d["type"] == vehicle:
                  return val in d.values()
          return False
      

      我们可以做一些测试:

      >>> check([{'type' :'car', 'color' : 'red', 'engine' : 'diesel'}], "car", "red")
      True
      >>> check([{'type' :'car', 'color' : 'red', 'engine' : 'diesel'}], "car", "blue")
      False
      >>> check([{'type' :'car', 'color' : 'red', 'engine' : 'diesel'}], "car", "diesel")
      True
      

      【讨论】:

        猜你喜欢
        • 2011-10-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-06
        • 2017-03-30
        • 2015-02-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多