python - What is the Pythonic way to map a sequence of one custom class to another? -


(...or, alternatively, pythonic version of c#'s select(...) method? )

given list l of custom class a (most?) pythonic way map each element of l different custom class b?

for example, following code it, pythonic way of doing it? note, real types have many properties.

l = [a('greg', 33), a('john', 39)]  def map_to_type_b(the_list):     new_list = []     item in the_list:         new_list.append(b(item.name, item.age))      return new_list  l2 = map_to_type_b(l) 

i'm coming c# background, use linq select or select() extensions method project source sequence new sequence of type b.

i it's part of job of b class determine how instance of arbitrary other class should transformed instance of b, use class method alternate constructor approach, e.g. follows:

class a(object):      def __init__(self, name, age):         self.name = name         self.age = age      def __repr__(self):         return 'a({0.name!r}, {0.age!r})'.format(self)   class b(a):      def __repr__(self):         return 'b({0.name!r}, {0.age!r})'.format(self)      @classmethod     def from_a(cls, inst):         return cls(inst.name, inst.age) 

you can use simple list comprehension or map convert list of 1 class another, e.g.:

>>> l = [a('greg', 33), a('john', 39)] >>> l [a('greg', 33), a('john', 39)]  >>> map(b.from_a, l)  # different, more memory-efficient, in 3.x [b('greg', 33), b('john', 39)]  >>> [b.from_a(a) in l]  # works (nearly) identically in 2.x , 3.x [b('greg', 33), b('john', 39)] 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -