将值附加到特定类型的列表中

时间:2015-05-10 16:19:04

标签: python

我有一个Agent课程,如下所示:

import Point
import random

class Agent(object):
    """description of class"""

    locationX = 0
    locationY = 0

    def __init__(self, point = None):
        self.locationX = point.x
        self.locationY = point.y

    def GenerateAgents(numberOfAgents):
        agentList = []
        while len(agentList) < numberOfAgents:

            point = Point.Point()
            point.x = random.randint(0, 99)
            point.y = random.randint(0, 99)

            agent = Agent(point)
            agentList.append(agent)
        return agentList

    def AppendValue(agentList):
        for item in agentList:
            item.append(False)
        return agentList

    def GetAgentCoordinate(agentList, agentIndex):
        for agent in agentList:
            return agentList[agentIndex]

除了Point类之外:

import math

class Point(object):
    """description of class"""

    x = 0
    y = 0

    def __init__(self, x = None, y = None):
        self.x = x
        self.y = y

    def GetDistance(point1, point2):
        return math.sqrt(math.pow(point1.x - point2.x, 2) +
                         math.pow(point1.y - point2.y))

以下是Main类:

import Agent
import Point

if __name__ == "__main__":

    agentList = Agent.Agent.GenerateAgents(100)
    selectedAgent = Agent.Agent.GetAgentCoordinate(agentList, 10)
    myList = Agent.Agent.AppendValue(agentList)    //ERROR!

我要将False值附加到agentList的每个子列表中。但这里是追溯。我的Appendvalue课程已定义Agentappend已考虑list,但我没有解决问题。

这听起来可能是一个愚蠢的错误......请你清理一下这个案子吗?

Traceback (most recent call last):
File "C:\Program Files\Microsoft Visual Studio  12.0\Common7\IDE\Extensions\Microsoft\Python Tools for Visual Studio\2.1\visualstudio_py_util.py", line 106, in
exec_file
exec_code(code, file, global_variables)
File "C:\Program Files\Microsoft Visual Studio 12.0\Common7\IDE\Extensions\Microsoft\Python Tools for Visual Studio\2.1\visualstudio_py_util.py", line 82, in exec_code
exec(code_obj, global_variables)  File "C:\Users\Matinking\documents\visual studio 2013\Projects\NeuroSimulation\NeuroSimulation\Main.py", line 8, in <module>
myList = Agent.Agent.AppendValue(agentList)  File    "C:\Users\Matinking\documents\visual studio 2013\Projects\NeuroSimulation
\NeuroSimulation\Agent.py", line 28, in AppendValue
item.append(False)
AttributeError: 'Agent' object has no attribute 'append'
Press any key to continue . . .

1 个答案:

答案 0 :(得分:2)

我认为错误就在这里:

def AppendValue(agentList):
    for item in agentList:
        item.append(False) #Precisely here
    return agentList

您正在尝试执行列表方法,而itemagentList(代理对象列表)中的元素(不是列表)

另外,我发现您可以优化以下代码:

def GetAgentCoordinate(agentList, agentIndex):
        for agent in agentList:
            return agentList[agentIndex]

只是:

def GetAgentCoordinate(agentList, agentIndex):
    return agentList[agentIndex]