背景
假设我有一些 Info 类,它存储用户定义的一堆属性,例如:
class Info:
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
def __getitem__(self, key):
return getattr(self, key)
我有一个 Info 实例列表,比方说:
all_keys = [Info(a=1, b='y', c=0),
Info(a=2, b='y', c=1),
Info(a=3, b='n', c=2),
Info(a=2, b='y', c=3)]
我想根据 a、b、c 的某些条件从列表 all_keys 中选择项目.我做了以下功能:
def keys_with(all_keys, **kwargs):
out = []
for info in all_keys:
flag = 1
for k, v in kwargs.items():
if info[k] != v:
flag = 0
break
if flag:
out.append(info)
return out
预期的使用和输出
我想做类似的事情:my_keys = keys_with(all_keys, a=2, b='y')。当前函数 keys_with 给出所需的输出:
[Info(c=1, a=2, b=y), Info(c=3, a=2, b=y)]
问题
函数 keys_with() 对于如此简单的事情来说是丑陋的:它使用标志、嵌套循环,并且看起来非常非 pythonic。我相信有更好的方法可以更紧凑、更符合 python 的方式编写它。感谢任何帮助或提示!
请您参考如下方法:
类似于:
def keys_with(all_keys, **kwargs):
def matches(info):
"""
Iterates over all `kwargs` outside and returns True
only if all the key/values within kwargs are present in info.
"""
return all(getattr(info, x) == y for x, y in kwargs.items())
return [info for info in all_keys if matches(info)]
