在http://underscorejs.org/ ,有一个 underscorejs 实用程序 where
,
_.where(listOfPlays, {author: "Shakespeare", year: 1611}
返回,
[{title: "Cymbeline", author: "Shakespeare", year: 1611},
{title: "The Tempest", author: "Shakespeare", year: 1611}]
如何在 python 中执行此操作而不使用 for in
迭代?
最佳答案
我个人想使用列表推导式。但它确实涉及 for
和 in
:
>>> listOfPlays = [{'title': x, 'author': x, 'year': 1611} for x in ('Shakespeare', 'someone')]
>>> listOfPlays
[{'author': 'Shakespeare', 'year': 1611, 'title': 'Shakespeare'}, {'author': 'someone', 'year': 1611, 'title': 'someone'}]
>>>
>>> [x for x in listOfPlays if x['author'] == 'Shakespeare' and x['year'] == 1611]
[{'author': 'Shakespeare', 'year': 1611, 'title': 'Shakespeare'}]
或者,您可以使用 filter
:
>>> filter(lambda x: x['author'] == 'Shakespeare' and x['year'] == 1611, listOfPlays)
[{'author': 'Shakespeare', 'year': 1611, 'title': 'Shakespeare'}]
已编辑:请注意,上述示例是在 Python 2 中计算的。在 Python 3 中,内置函数 filter
返回一个可迭代对象而不是一个列表。
关于python - javascript 的 _.where 在 python 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33747992/