如何将对象转换为iterable(list)?

时间:2018-05-21 06:06:05

标签: python python-2.7

我想将对象转换为可迭代的对象。

我有格式

的输出
>>>result[0]    
<Particle [0.015270307267929021, -0.0009933688866323714, -0.004208897534490854, -0.011275132115610775, 0.0029132053067140572, 0.005608170262839968, 0.0005401367846572976, -0.013393458586919493, 0.0003998091070805884, 0.0002900137732599478]>

问题的完整代码是

from fstpso import FuzzyPSO 

def example_fitness( particle ):
    return sum(map(lambda x: x**2, particle))

if __name__ == '__main__':

    dims = 10
    FP = FuzzyPSO()
    FP.set_search_space( [[-10, 10]]*dims ) 
    FP.set_fitness(example_fitness) 
    result =  FP.solve_with_fstpso()
    print "Best solution:", result[0]
    print "Whose fitness is:", result[1]

我想使用result [0]作为列表。 Source

2 个答案:

答案 0 :(得分:2)

根据您的评论说明它是fstpso.pso.Particle,如果您只是调用以下内容,您将能够在不更改原始源代码的情况下将其用作迭代器。

variable = result[0].X
for i in variable:
    print(i)

原始源代码表示__repr__()函数只是打印self.X值,这是一个列表。

def __repr__(self):
return "<Particle %s>" % str(self.X)

答案 1 :(得分:1)

fstpso.pso.Particle对象如下:

class Particle(object):

    def __init__(self):
        self.X = []
        self.V = []
        self.B = []
        self.MarkedForRestart = False
        self.CalculatedFitness = sys.float_info.max
        self.FitnessDevStandard = sys.float_info.max
        self.CalculatedBestFitness = sys.float_info.max
        self.SinceLastLocalUpdate = 0

        self.DerivativeFitness = 0
        self.MagnitudeMovement = 0
        self.DistanceFromBest = sys.float_info.max
        self.CognitiveFactor = 2.
        self.SocialFactor = 2.
        self.Inertia = 0.5

        # support for PPSO
        self.MaxSpeedMultiplier = .25
        self.MinSpeedMultiplier = 0

    def __repr__(self):
        return "<Particle %s>" % str(self.X)

    def __str__(self):
        return "\t".join(map(str, self.X))

来自https://github.com/aresio/fst-pso/blob/master/fstpso/pso.py

你想要的是:

result[0].X