这是我的fetch_all_agents
方法,被认为是一次性提供所有代理坐标:
def fetch_all_agents(number_of_agents = None):
agentList = []
agentConfig = configparser.ConfigParser()
agentConfig.readfp(open(r'SwarmSimulator\configFile.txt'))
random_option = agentConfig.get('Agent Generation', "random_option")
if(random_option == "True"):
agentList = agentObj.generate_agents(number_of_agents)
elif(random_option == "False"):
with open(r"SwarmSimulator\agentListFile.txt") as f:
tempList = [list(ast.literal_eval(line)) for line in f]
pointObj = Point.Point()
for innerList in tempList:
pointObj.x = innerList[0]
pointObj.y = innerList[1]
agentObj = Agent.Agent(pointObj)
agentList.append(agentObj)
return agentList
我将计划另一种方法,让我们将其命名为fetch_single_agent
以从列表中读取一个代理,即正确的代理在最后一个代理旁边保留的代理。将发电机考虑在内是合理的。
请您指导我为上述方法实现生成器驱动的版本,正如我所解释的那样,可以按顺序从列表中获取代理吗?
答案 0 :(得分:1)
yield
只需agentObj
:
for innerList in tempList:
pointObj.x = innerList[0]
pointObj.y = innerList[1]
agentObj = Agent.Agent(pointObj)
yield agentObj
agent_gen = fetch_all_agents(5)
for agent in agent_gen:
print(agent)
或者使用下一个获得一个代理:
agent_gen = fetch_all_agents(5)
ag_1 = next(agent_gen)