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:
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.