如何使用Python根据一组可变条件过滤列表列表? [英] How to filter a list of lists based on a variable set of conditions with Python?

查看:101
本文介绍了如何使用Python根据一组可变条件过滤列表列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与此帖子相关的问题.

我需要帮助,以根据一组可变的条件来过滤列表.

I need help to filter a list of lists depending on a variable set of conditions.

以下是列表的一部分:

ex = [
    # ["ref", "type", "date"]
    [1, 'CB', '2017-12-11'],
    [2, 'CB', '2017-12-01'],
    [3, 'RET', '2017-11-08'],
    [1, 'CB', '2017-11-08'],
    [5, 'RET', '2017-10-10'],
]

我想应用像list(filter(makeCondition, ex))这样的最终处理方法,其中makeCondition(myList, **kwargs)函数返回一个布尔值,该布尔值可以过滤列表.

I want to apply a final treatment like list(filter(makeCondition, ex)) where makeCondition(myList, **kwargs) function returns a boolean that enables to filter the list.

按照此帖子中的建议,我在构建此功能时遇到了麻烦,因为** kwargs中定义了许多条件字典是可变的.

I have troubles building this function as adviced in this post, as the number of conditions defined in the **kwargs dictionnary is variable.

条件集示例:

conditions = {"ref": 3}
conditions = {"ref": 1, "type": "CB"}

这是一个开始:

def makeConditions(myList, **p):

    # For each key:value in the dictionnary
    for key, value in p.items():

        if key == "ref":
            lambda x: x[0] == value
        elif key == "type":
            lambda x: x[1] == value
        elif key == "date":
            lambda x: x[2] == value

    # return chained conditions...

list(filter(makeConditions, ex))

我不理解上面提到的帖子中试图给出各种注释的逻辑思路...我是否必须为每个子列表执行filter()函数,还是有可能对整个全局列表执行它? ?任何建议都将非常受欢迎!

I don't get the logical idea that various comments attempted to give in the post mentioned above... Do I have to execute the filter() function for each sublist or is it possible to do it for the whole global list? Any advices will be very welcome!

推荐答案

我只是简单地创建一个返回条件的函数:

I would simply make a function that returns the conditional:

def makeConditions(**p):
    fieldname = {"ref": 0, "type": 1, "date": 2 }
    def filterfunc(elt):
        for k, v in p.items():
            if elt[fieldname[k]] != v: # if one condition is not met: false
                return False
        return True
    return filterfunc

然后您可以通过以下方式使用它:

Then you can use it that way:

>>> list(filter(makeConditions(ref=1), ex))
[[1, 'CB', '2017-12-11'], [1, 'CB', '2017-11-08']]
>>> list(filter(makeConditions(type='CB'), ex))
[[1, 'CB', '2017-12-11'], [2, 'CB', '2017-12-01'], [1, 'CB', '2017-11-08']]
>>> list(filter(makeConditions(type='CB', ref=2), ex))
[[2, 'CB', '2017-12-01']]

这篇关于如何使用Python根据一组可变条件过滤列表列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆