与此相关的问题post .
我需要帮助来根据一组可变条件过滤列表列表。
这是列表的摘录:
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)
函数返回一个 bool 值,它能够过滤列表。
我无法按照 post 中的建议构建此功能,因为 **kwargs 字典中定义的条件数量是可变的。
条件集示例:
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()
函数或者是否可以为整个全局名单做这件事?任何建议都将非常受欢迎!
最佳答案
我会简单地创建一个返回条件的函数:
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
然后你就可以这样使用了:
>>> 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 - 如何使用 Python 根据可变条件集过滤列表列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47769705/