Python 如果关键字可以为“无”,则使用“理解”筛选词典列表?
我想使用列表理解过滤字典列表 既然arg1或arg2可能为None,那么有没有更好的方法来编写此代码,这样我就不必在执行列表理解之前先检查变量是否为NonePython 如果关键字可以为“无”,则使用“理解”筛选词典列表?,python,dictionary,Python,Dictionary,我想使用列表理解过滤字典列表 既然arg1或arg2可能为None,那么有没有更好的方法来编写此代码,这样我就不必在执行列表理解之前先检查变量是否为None a = list of dictionaries if arg1 is None and arg2 is None: result = a elif arg1 is not None and arg2 is not None: result = [d for d in a if d['key1'] == arg1 and
a = list of dictionaries
if arg1 is None and arg2 is None:
result = a
elif arg1 is not None and arg2 is not None:
result = [d for d in a if d['key1'] == arg1 and d['key2'] == arg2]
elif arg1 is not None and arg2 is None:
result = [d for d in a if d['key1'] == arg1]
elif arg1 is None and arg2 is not None:
result = [d for d in a if d['key2'] == arg2]
作为理解的一部分,您可以检查“无”。这应涵盖上述四种情况:
result = [d for d in a if (arg1 is None or arg1 == d['key1']) and (arg2 is None or arg2 == d['key2'])]
您可以尝试filter,如果找不到任何内容,它将返回空值:
result = list(filter(lambda x: x['key1'] == arg1, a))
result += list(filter(lambda x: x['key2'] == arg2, a))
您可以分两个单独的步骤筛选a:
result = a.copy()
if arg1 is not None:
result = [d for d in result if d['key1'] == arg1]
if arg2 is not None:
result = [d for d in result if d['key2'] == arg2]
虽然对于a的较长长度,这可能会较慢。您能提供a吗?一个字典列表的例子,以及什么是arg1和arg2在我的测试中,当arg1或arg2都以非无方式通过时,这项功能会起作用,但当arg1和arg2都以无方式通过时,这项功能似乎会失败,因为无方式返回所有内容,但不返回任何内容,或者无方式返回交叉点,但返回并集。啊,明白了。谢谢你的检查!这个答案正是我所寻找的,它是如此合乎逻辑,我是如此接近,但我迷失了,因为我是绝望的,寻找一个完全不同的方法。谢谢!