Skip to main content
 首页 » 编程设计

python之使用许多键值对过滤 python 中的列表

2024年10月01日6unruledboy

我有一个如下所示的列表:

commands = [ 
{'command': "start app", 'action': "monitor", 'max-threshold': True, 'zero-failcount': True, 'started': True, 'stopped': False, 'failed': False}, 
{'command': "read log", 'action': "monitor", 'max-threshold': False, 'zero-failcount': True, 'started': True, 'stopped': False, 'failed': False}, 
{'command': "kill app", 'action': "monitor", 'max-threshold': True, 'zero-failcount': True, 'started': True, 'stopped': False, 'failed': False} 
] 

而且我想进行过滤,以便在新列表中只看到少数案例。例如,只有 max-threshold 为 true、零失败计数为 true 的那些。我该怎么做?我正在使用 Python 2.7。

请您参考如下方法:

使用 list comprehension.

例如,像这样的东西:

[command for command in commands if command['max-threshold']]