python - javascript 的 _.where 在 python 中

标签 python dictionary

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 迭代?

最佳答案

我个人想使用列表推导式。但它确实涉及 forin:

>>> 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/

相关文章:

python - 如何将python字典保存到json文件中?

json - 将嵌套字典转换为可图形格式

python - 修改按位 Karatsuba 算法以处理负数的最佳方法是什么?

python - 如何将 kwargs 传递给 argparse

Python:除非在引号内,否则用多字符定界符拆分字符串

python - 字典键的顺序可以被认为是随机排列吗?

java - 嵌套映射结构

python - Pandas DataFrame 替换给定索引值的 1 列中的值

python - Django 应用程序消耗服务器中的内存

python - 如何在 python-3.x 中使用字典格式化字符串?