Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter array of objects in Python

I'm using Python to dig through a pretty big project and dig up information about it. I'm able to create an array of ProjectFiles, however I'm having a hard time figuring out how to filter it.

class ProjectFile:
    def __init__(self, filename: str,
                 number_of_lines: int,
                 language: str,
                 repo: str,
                 size: int):
        self.filename = filename
        self.number_of_lines = number_of_lines
        self.language = language
        self.repo = repo
        self.size = size

How would I filter an array of ProjectFile objects for a specific repo?

For instance, let's say I wanted to filter for objects whose repo property is SomeCocoapod.

I've looked for examples of filter, but everything I've found uses simple examples like lists of str or int.

like image 357
Adrian Avatar asked Dec 06 '25 17:12

Adrian


1 Answers

You can select attributes of a class using the dot notation.

Suppose arr is an array of ProjectFile objects. Now you filter for SomeCocoapod using.

filter(lambda p: p.repo == "SomeCocoapod", arr)

NB: This returns a filter object, which is a generator. To have a filtered list back you can wrap it in a list constructor.

As a very Pythonic alternative you can use list comprehensions:

filtered_arr = [p for p in arr if p.repo == "SomeCocoapod"]
like image 82
Hielke Walinga Avatar answered Dec 09 '25 13:12

Hielke Walinga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!