You can get a list of all matching elements with a list comprehension:
[x for x in myList if x.n == 30] # list of all elements with .n==30
If you simply want to determine if the list contains any element that matches and do it (relatively) efficiently, you can do
def contains(list, filter):
for x in list:
if filter(x):
return True
return False
if contains(myList, lambda x: x.n == 3) # True if any element has .n==3
# do stuff
Answer from Adam Rosenfield on Stack OverflowYou can get a list of all matching elements with a list comprehension:
[x for x in myList if x.n == 30] # list of all elements with .n==30
If you simply want to determine if the list contains any element that matches and do it (relatively) efficiently, you can do
def contains(list, filter):
for x in list:
if filter(x):
return True
return False
if contains(myList, lambda x: x.n == 3) # True if any element has .n==3
# do stuff
Simple, Elegant, and Powerful:
A generator expression in conjuction with a builtin… (python 2.5+)
any(x for x in mylist if x.n == 10)
Uses the Python any() builtin, which is defined as follows:
any(iterable)
->Return True if any element of the iterable is true. Equivalent to:
def any(iterable):
for element in iterable:
if element:
return True
return False
Like ok... the title said it all. For example : I have a list filled by class name Food. The class uniqueness are defined by name and price attribute. And I create a method to check if the Food is free. the question is how do I use the method to filter the list of Food class using the free checking method of food class?
@dataclass
class Food:
name : str
price : int
def isfree(self):
return self.price == 0
food_list = [Food(name = "curry", price = 5), Food(name = "sushi", price = 0)]
filtered_list = filter(Food.isfree, food_list) # got error TypeError: isfree() takes 0 positional arguments but 2 were givenFiltering object sets in a Python function
Filter list of object with condition in Python - Stack Overflow
Filtering list of objects on multiple conditions
Filtering an array of JSON objects by multiple properties
Videos
Since you specifically asked about filtering the list you have, you can use filter builtin with lambda to filter out the elements from the list.
>>> list(filter(lambda x: x.get('text', '')=='abc', listpost))
[{'post_id': '01', 'text': 'abc', 'time': datetime.datetime(2021, 8, 5, 15, 53, 19), 'type': 'normal'}]
But I'd recommend to filter it out upfront before actually appending it to the list, to avoid unnecessary computations due to the need to re-iterate the items i.e. appending only the items that match the criteria.
Something like this:
for post in get_posts("myhealthkkm", pages=1):
if <post match the condition>:
listposts.append(post) # append the post
simple like that:
filtered_list = [e for e in listpost if e['text'] == 'abc']