I'm about to work my way into python's 3.5 lambda notation and I'm wondering wether nested loops can simply be replaced with a lambda one-liner. e.g.: I have this simple dummy class hierarchy:
class Resource:
def __init__(self, name="foo"):
self.name = name
class Course:
def __init__(self):
self.resources = list()
class College:
def __init__(self):
self.courses = list()
I have an instance of Collegewith multiple Courses and Resources as my starting point.
college = College()
Now if I want a listof all the Resources in my College I could easily do this with 2 for-loops:
all_resources = list()
for course in college.courses:
for resource in course.resources:
all_resources.append(resource)
This is indeed very simple but I wondered whether I could also achieve this by doing something like this:
all_resources = list(map(lambda r: r, [c.resources for c in college.courses]))
But unfortunately this gives me a listof lists and not a listof Resources, what I wanted to achieve. Is lambda suitable for something like that?
What would be the most pythonic way for a operation like this?