如何按列表理解和最小/最大功能查询列表

时间:2015-05-24 17:50:22

标签: python python-2.7 python-3.x

我有两个Python课程:AgentGroup ...

每个Group都有一个centerGroup属性,加上一个静态的组列表,即GroupList

以下是Group课程的简要概述:

import Agent

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

GroupIdentifier = 1
GroupThreshold = 10
GroupList = []


def __init__(self, agentList = None ,groupCenter = None, gruopIdentifier = None):
    global GroupIdentifier
    global GroupList
    self.groupIdentifier = GroupIdentifier
    Group.GroupIdentifier += 1
    Group.GroupList.append(self)
    self.groupCenter = groupCenter
    self.agentList = agentList

此外,在Agent类中,我将找到与centerGroup中的组对应的所有groupList属性中典型代理的最小欧几里德距离......(有一个偏移,是GAMMA_TRESHOLD)...

可以描述Agent类的相关部分,如下面的代码段:

import Group

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

GAMMA_TRESHOLD = 20

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

def get_agent_distance_from_groupCenter(self, object):
    return math.sqrt(math.pow(self.locationX - point.x, 2) +
                     math.pow(self.locationY - point.y, 2))

def gamma_condition(self):
    #I KNOW THIS IMPLEMENTATION IS WRONG... JUST GOTTA SHOW THE TARGET!
    return Group.Group.GroupList[Group.Group.GroupList.index(min(get_agent_distance_from_groupCenter(agent, group.groupCenter) - GAMMA_TRESHOLD))]

从数学方面来看,问题是最小化以下规范并引入其centerGroup最接近代理的组:

min \norm{centerGroup_{i} - agent - TRESHOLD}

请您帮助我通过列表理解gamma_condition来编写此类查询(Python方法的有效处理)?!

1 个答案:

答案 0 :(得分:0)

总而言之,在适当关注其他人缺乏任何更好的想法的情况下,我的调查导致了以下问题的解决方案:

def gamma_condition(self):
    temp = []
    maxValue = 0
    temp = [[item.groupIdentifier, JOIN_TRESHOLD - self.get_agent_distance_from_groupCenter(item.groupCenter)] for item in Group.Group.GroupList]
    for item in temp:
        maxValue = max(float(i) for i in item[1])
    if maxValue > 0:
        index = temp.index(maxValue)
        NearestGroupIdToJoin = temp[index][0]    
        return NearestGroupIdToJoin
    else:
        return None