How do you filter an 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.

How do you filter an array of objects in python?

RoadRunner

24.9k6 gold badges36 silver badges72 bronze badges

asked May 3, 2020 at 15:40

How do you filter an array of objects in python?

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"]

answered May 3, 2020 at 15:48

Hielke WalingaHielke Walinga

2,4741 gold badge15 silver badges25 bronze badges

1

Lets say you had this simple list of two ProjectFile objects:

projects = [
    ProjectFile(
        filename="test1.txt",
        number_of_lines=1,
        language="English",
        repo="repo1",
        size=1,
    ),
    ProjectFile(
        filename="test2.txt", 
        number_of_lines=2, 
        language="German", 
        repo="repo2", 
        size=2
    ),
]

You could then filter out repo1 using the repo attribute inside a list comprehension:

filtered = [project for project in projects if project.repo == "repo1"]

The above assumes you have overriden __str__ or __repr__ inside your ProjectFile class to give you a string representation of the filtered objects. Otherwise you will get something like [<__main__.ProjectFile object at 0x000001E879278160>] returned(which is fine if that's what you want to see). You can have a look at How to print instances of a class using print()? for more information.

answered May 3, 2020 at 15:48

How do you filter an array of objects in python?

RoadRunnerRoadRunner

24.9k6 gold badges36 silver badges72 bronze badges

Python filter Array of objects And print the label for each object, you could use a loop or a list comprehension.

We filter an array of ProjectFile objects for a specific repo. Select attributes of a class using the dot notation.

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

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


projects = [
    ProjectFile(
        filename="test1.txt",
        number_of_lines=1,
        language="English",
        repo="repo1",
        size=1,
    ),
    ProjectFile(
        filename="test2.txt",
        number_of_lines=2,
        language="German",
        repo="repo2",
        size=2
    ),
]

res = [project for project in projects if project.repo == "repo1"]

print([projects.repo + " " + projects.language for projects in res])

Output:

How do you filter an array of objects in python?

As a very Pythonic alternative you can use list comprehensions:

filtered_arr = [p for p in arr if p.repo == "SomeCocoapod"]

Source: stackoverflow.com

Do comment if you have any doubts or suggestions on this Python code.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

How do you filter an array of objects in python?

Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.

How do you filter an object in an array?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.

How do you filter an array of objects based on a property?

To filter an array of objects based on a property:.
Call the Array. filter() method on the array..
On each iteration, check if the object's property points to the specific value..
The Array. filter method will return an array with all objects that satisfy the condition..

How do you filter an array of strings in Python?

Filter a list of string using filter() method. filter() method accepts two parameters. The first parameter takes a function name or None and the second parameter takes the name of the list variable as values. filter() method stores those data from the list if it returns true, otherwise, it discards the data.

How do you filter a class object in Python?

Python filter().
filter() Syntax. Its syntax is: filter(function, iterable).
filter() Arguments. The filter() function takes two arguments:.
filter() Return Value. ... .
Example 1: Working of filter() ... .
Example 2: Using Lambda Function Inside filter() ... .
Example 3: Using None as a Function Inside filter().

Tải thêm tài liệu liên quan đến bài viết How do you filter an array of objects in python?