Underscore有一个方便的小功能,findWhere()可以用来查找列表中的某个结构,如
myList = [
{'name': 'Thor'},
{'name': 'Odin'},
{'name': 'Freya'},
{'name': 'Skadi'}
];
findWhere(myList, {'name': 'Skadi'});
结果:[{'name': 'Skadi'}]
更好的例子:
my_list = [
{'name': 'Thor',
'occupation': 'God of Thunder',
'favorite color': 'MY HAMMER'}
{'name': 'Skadi',
'occupation': 'Queen of the Ice Giants',
'favorite color': 'purpz'}
]
findWhere(my_list, {'name': 'Skadi'})
结果:
[{'name': 'Skadi',
'occupation': 'Queen of the Ice Giants',
'favorite color': 'purpz'}]
唉,我在python中找不到类似的东西。实现相同功能的pythonic方法是什么?
答案 0 :(得分:4)
您可以将其定义为generator:
def find_where(iterable, dct):
for item in iterable:
if all(item[key] == value for key, value in dct.items()):
yield item
my_list = [
{'name': 'Thor', 'age': 23},
{'name': 'Odin', 'age': 42},
{'name': 'Freya', 'age': 50},
{'name': 'Skadi', 'age': 23},
]
print list(find_where(my_list, {'age': 23}))
输出:
[{'age': 23, 'name': 'Thor'}, {'age': 23, 'name': 'Skadi'}]
有关表达式“肉”的详细信息,请参阅all()
和list comprehensions。
答案 1 :(得分:2)
我使用带有curried子集谓词的过滤器:
# assuming both key and values are hashable
subset = lambda subset: (lambda superset: set(subset.items()).issubset(set(superset.items())))
results = filter(subset(needle), haystack)
或者,如果dict的值可能不可清,则子集需要是:
subset_nh = lambda subset: (lambda superset: all(item in superset.items() for item in subset.items()))
results = filter(subset_nh(needle), haystack)