Astrid Astrid - 3 months ago 8
Python Question

Return multiple instances from an object in python

This question has no doubt been asked before, but I am not entirely sure how to search for it (since I do not know what it is called). So apologies in advance.

Alas, my problem is that I have a huge amount of objects

for i in range(1000):
M = subParts[0].get(parts['thing'][i])


Each
M
is an object that contains a lot of info about this model, now my job is to call four separate functions on this object, so that those functions can return four simple numbers as so:

for i in range(1000):
M = subParts[0].get(parts['thing'][i])
M.getItem1()
M.getItem2()
M.getItem3()
M.getItem4()


each of which returns a number, e.g.

4.5
5.7
3.7
2.9


My question is thus, what is an efficient way to do this? The above is very ugly but works, but there must be more efficient methods. Upon which I would just like to store the whole lot in a dictionary as so

myDict = { 0 : [4.5,5.7,3.7,2.9], ... , 999 : [2.5,3.7,5.7,2.9] }


Thanks.

Answer

Assuming that parts['thing'] is an ordered sequence that can be iterated over, you can use map to call subParts[0].get on each element of parts['thing'] so iterating over each M object could be done like this:

for M in map(subParts[0].get, parts['thing']):
    ...

Note that this will return a list in python 2 so using itertools.imap would be preferable.

To put it into dict comprehension you would just do:

stuff = {i:[M.getItem1(),
            M.getItem2(),
            M.getItem3(),
            M.getItem4()]
         for i,M in enumerate(map(subParts[0].get, parts['thing']))}
Comments