python:找出一个对象数组是否符合某些条件

时间:2017-11-21 20:31:55

标签: python json filter

我有一个像

这样的对象列表
[{'type' :'car', 'color' : 'red', 'engine' : 'diesel'}, {'type' : 'truck'...}

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

基本上我想创建一个允许您根据这些列表匹配规则的服务。就像用户可以定义一些我应用于返回true或false的列表的过滤器。

喜欢" color = red和engine = diesel" ......就像你在prolog中可以做的一样。我看着pyke,但似乎太复杂了

4 个答案:

答案 0 :(得分:1)

您可以构建列表推导,仅选择符合预期条件的元素:

my_objects = [{'type' :'car', 'color' : 'red', 'engine' : 'diesel'}]

print([x for x in my_objects if x['type'] == 'car' and x['color'] == 'red'])

答案 1 :(得分:0)

只需使用function创建for-loop

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

答案 2 :(得分:0)

我更喜欢列表理解:

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()]

答案 3 :(得分:0)

假设:

>>> 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的{​​{1}}进行过滤:

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'}]