我想使用map函数计算质量中心。我不想使用循环。帮助底部的两行?

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 Center of Mass of List
# The following is pseudocode, does not actually work
SumOfMass = sum(objList[:].mass)
CenterOfMassX = sum(objList[:].x.*objList[:].mass)/SumOfMass

最佳答案

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


同样,您可以这样填充objList

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


注意,range仅接受整数参数。

附言mapfor循环。

关于python - 使用map处理python中的对象列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3941486/

10-08 23:30