memo
memo

Reputation: 3724

convert a list containing objects, to a list containing a specific function or properties of those objects

given that:

obj_list = [obj0, obj1, obj2, obj3...]

I'd like:

names_list = [obj0.name(), obj1.name(), obj2.name(), obj3.name()...]
paths_list = [obj0.path(), obj1.path(), obj2.path(), obj3.path()...]

so for debug purposes I can do:

print names_list

or

if my_path not in paths_list ...

of course I could just do

name_list =[]
path_list = []
for obj in obj_list:
    name_list.append(obj.name())
    path_list.append(obj.path())

But then I might as well write this in C. Surely there's a python way of doing this in one little command, but I couldn't find it.

I'm using python 2.7 by the way

Upvotes: 0

Views: 58

Answers (3)

thefourtheye
thefourtheye

Reputation: 239513

You can use operator.methodcaller, like this

from operator import methodcaller
get_name, get_path = methodcaller("name"), methodcaller("path")
names, paths = map(get_name, obj_list), map(get_path, obj_list)

Upvotes: 4

wnnmaw
wnnmaw

Reputation: 5534

The (syntactically) easy way of doing this in Python is with map()

names_list = map(lambda x: x.name(), obj_list)

Upvotes: 4

Wander Nauta
Wander Nauta

Reputation: 19635

Sounds like a job for list comprehensions.

names_list = [obj.name() for obj in obj_list]

Upvotes: 7

Related Questions