开发者

Python: sub list of items depending on a certain value of the items, e.g. boolean

开发者 https://www.devze.com 2023-03-21 21:23 出处:网络
I have a list of similar objects, some of them have a certain value set, here more specifically a boolean flag:

I have a list of similar objects, some of them have a certain value set, here more specifically a boolean flag:

myList = [WhatEver(..., T开发者_运维问答rue, ...), WhatEver(..., True, ...), WhatEver(..., False, ...), WhatEver(..., True, ...), WhatEver(..., False, ...), ...]

Is there a painless way in Python to get a sub list of items whose value is set to a specific value, here either True or False?


Yes, there is. List comprehensions are a very good fit for this:

[item for item in myList if item.flag]
[item for item in myList if not item.flag]

where flag is the name of WhatEver's field that you want to check.


Use filter:

filtered_list = filter(lambda item: item.flag, myList)
0

精彩评论

暂无评论...
验证码 换一张
取 消