Use a list comprehension:
[y for x,y in A if x>2]
Demo:
>>> A=[(1,'A'),(2,'H'),(3,'K'),(4,'J')]
>>> [y for x,y in A if x>2]
['K', 'J']
>>>
Answer from U13-Forward on Stack OverflowFiltering list of objects on multiple conditions
Filter instance of a class with a list of conditions
Querying Flask SQL Alchemy by multiple parameters
Multiple conditions in python filter function
Videos
Hi all, interested in your approaches and suggestions to this problem.
Let's say I have created a custom Player class that contains many attributes relating to a particular sportsperson's characteristics:
@dataclass
class Player:
id: int
first_name: str
last_name: str
age: int
height: int
weight: int
team: int
games_played: int
...If I create a small (~500) length list of these objects and then want to filter on multiple conditions, what's the best way for me to do that?
Of course, in a one off situation I could write something like:
filtered = [player for player in player_list if 20 <= player.age < 25 and player.height > 180 and player.team == "Rovers"]
This gives me the flexibility to filter exactly how I'd like but it's not the most glamorous solution in my opinion, especially if I want to try out lots of different filters.
I had a thought that this might be easier to by creating something like a PlayerFilter class which can be instantiated and then have filters added to a dict attribute or similar, and then can be applied to a list of players and return the filtered list. This seems more Pythonic to me but also seems slightly overkill and I'm looking for the most straightforward and intuitive way to filter these values. I'm imagining if a random python user was to use my package with this filter implementation, I'm not sure if that would make sense.
Is the complexity a side effect of using a list of objects to store my data as opposed to something like a dataframe? I've considered this too but I want to maintain the ability to call the methods that I've created for my custom player class on any filtered output.
Let me know what you think!