本文介绍了在 python 中模拟 findWhere() 的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Underscore 有一个方便的小函数,findWhere() 可以用来在一个列表喜欢
Underscore has a handy little function, findWhere() which can be used to find a certain structure in a list like
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 方式是什么?
Alas, I cannot find anything similar in python. What would be a pythonic way to implement the same functionality?
推荐答案
您可以简单地将其定义为 发电机:
You could simply define this as a 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 详细了解表达.
这篇关于在 python 中模拟 findWhere() 的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!