开发者

Using map to process a list-of-objects in python

I want to calculate the center-of-mass using the map function. I don't want to use for loops. Help with bottom two lines?

class Obj():  
    def __init__(self, mass = 0., x = 0., y = 0.):    
        self.mass = mass    
        self.x = x    
        self.y = y    

# Create List of Objects    
objList = []
n = 0    
for i in range(0,10):    
    for j in range(0,10):    
        objList.append(Obj(i*j,i,j))    

# Calculate开发者_Python百科 Center of Mass of List
# The following is pseudocode, does not actually work
SumOfMass = sum(objList[:].mass)       
CenterOfMassX = sum(objList[:].x.*objList[:].mass)/SumOfMass    


You can't do the last two lines unless you abandon your anti-for prejudice.

SumOfMass = sum(obj.mass for obj in objList)       
CenterOfMassX = sum(obj.x * obj.mass for obj in objList)/SumOfMass 

With py2k (which are you using?), map(func, alist) is equivalent to [func(v) for v in alist] i.e. it returns a list. You need two scalar answers, not one or two vectors. What func did you have in mind? Why do you want to calculate the center of mass using the map function?


sumofmass = sum(i.mass for i in objList)
centre = sum(i.x * i.mass for i in objList)/sumofmass

also, you could populate your objList like this:

objList = [Obj(i*j, i, j) for in range(10) for j in range(10)]

Note, that range takes only integer arguments.

P.S. map is a for loop.


If you are really dead set against using for, you can use the attrgetter function from the operator module. E.G.:

from operator import attrgetter
mass_of = attrgetter('mass')
SumOfMass = sum(map(mass_of, objList))

However, doing so runs contrary to the dictates of Python style (as does using camelCase variables — normally you name them like_this). It's more or less acceptable to use map if the thing you need to access is already in the form of a function which takes the sequence element as its only parameter. In other words, if you can call map(some_function, sequence) without having to jump through any hoops like those above to get some_function, then it's okay.

For other situations (which is most of them), it's considered preferable or mandatory to use a list-comprehension style as exemplified in some of the other answers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜