1

I have a class called Interval for which I want to create multiple interval objects from a list of intervals. How do I do it with map ?

class Interval(object):
    def __init__(self, s=0, e=0):
        self.start = s
        self.end = e

intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]]

I tried to do:

objs = map(Interval, intervals)

But this sends the full interval as the first parameter rather than the inputs to the class individually.

2
  • objs = list(map(Interval, intervals)) should work Commented Jun 7, 2017 at 23:00
  • @AlanLeuthard: it works, but then s will get a list as input, and e will be 0 for all cases... Commented Jun 7, 2017 at 23:01

3 Answers 3

2

You can use starmap from itertools:

from itertools import starmap

objs = starmap(Interval,intervals)

Mind that starmap works lazily (like map in Python-3.x) and that you will need to materialize it, for instance using list(..):

>>> list(objs)
[<__main__.Interval object at 0x7efbf7e82358>, <__main__.Interval object at 0x7efbf7e82390>, <__main__.Interval object at 0x7efbf7e823c8>, <__main__.Interval object at 0x7efbf7e82400>, <__main__.Interval object at 0x7efbf7e82438>]

If you do not want to use the itertools library, an equivalent is:

objs = map(lambda x: Interval(*x),intervals)

As far as I know, that's why they call it starmap: because of the asterisk if you would use a lambda expression.

Sign up to request clarification or add additional context in comments.

2 Comments

Are you everywhere at this time of the night? hahaha, and also better answer... I must admit
Ah! starmap, this is what I was looking for. Thanks!
2

This worked for me.

>>> objs = []
>>> for interval in intervals:
...     objs.append(Interval(*interval))
... 
>>> objs
[<__main__.Interval object at 0x013E67D0>, <__main__.Interval object at 0x013E6910>, <__main__.Interval object at 0x013E68F0>, <__main__.Interval object at 0x013E6870>, <__main__.Interval object at 0x013E6950>]
>>> objs[0]
<__main__.Interval object at 0x013E67D0>
>>> objs[0].start
1
>>> objs[0].end
2
>>> 

Comments

0

Maybe you can try also the old-school way:

class Interval(object):
    def __init__(self, s=0, e=0):
        self.start = s
        self.end = e


def map_intervals(intervals):
        ret = []
        for inter in intervals:
          ret.append(Interval(inter[0],inter[1]))
        return ret
inters = [[1,2],[3,5],[6,7],[8,10],[12,16]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.