1

所以我有一个Education附加到UserProfile. 这个模型的工作原理和一个假设一样:User已经去了不同地区的几所学校。

我正在尝试做的是根据用户的去向进行“评分”。基本上,如果他们上同一所学校,他们会得到 10 分,同一个城市,5 分,同一个州,2 分,依此类推。

我已经做了一些功能来尝试这个,但我失败了。有什么建议吗?

info = {}
def edu_info(user1):
    user_1_cities = []
    user_1_schools = []
    user_1_state = []
    first_one = Education.objects.filter(owner=user1)
    for i in first_one:
        user_1_cities.append(str(i.city))
        user_1_schools.append(str(i.school))
        user_1_state.append(str(i.state))
        info[str(i.owner.username)] = {}
        info[str(i.owner.username)]['cities'] = user_1_cities
        info[str(i.owner.username)]['schools'] = user_1_schools
        info[str(i.owner.username)]['state'] = user_1_state
    return info

def check_match(user1, user2):
    match_score = {}    
    first_info = edu_info(user1)
    dict = edu_info(user2)
    for item in dict:
        cities = dict[item]['cities']
        #user2 = item
        #print cities
        for city in cities:
            if city in first_info['jmitchel3']['cities']:
                match_score['user'] = 'jmitchel3'
                match_score['user2'] = str(user2.user.username)
                match_score['city'] = city
                print "here! " + str(city)
            else:
                print "not here! " + str(city)

    return match_score




check_match(j,t)
4

1 回答 1

1

这样的事情怎么样?

从收集有关单个用户的信息的函数开始,并为该用户返回单个字典:

def edu_info(user1):
    user_1_cities = []
    user_1_schools = []
    user_1_state = []
    first_one = Education.objects.filter(owner=user1)
    for i in first_one:
        user_1_cities.append(str(i.city))
        user_1_schools.append(str(i.school))
        user_1_state.append(str(i.state))
    info = {}
    info['cities'] = user_1_cities
    info['schools'] = user_1_schools
    info['states'] = user_1_state
    return info

然后,有一个单独的函数,为两个用户中的每一个调用一次信息收集函数,并使用该信息计算点数。

def check_match(user_1, user_2)
    info_1 = edu_info(user_1)
    info_2 = edu_info(user_2)
    school_points = similarity_points(info_1["schools"], info_2["schools"], 10)
    city_points = similarity_points(info_1["cities"], info_2["cities"], 5)
    state_points = similarity_points(info_1["states"], info_2["states"], 2)
    return school_points + city_points + state_points

check_match函数的核心被卸载到它自己的辅助函数中。此函数查找两个属性列表的交集,并将共享属性的数量乘以某个点值。它通过将属性列表转换为集合然后使用集合交集运算符来做到这一点。

因此,similarity_points(["MN","OR","PA", "NJ"],["AZ","NJ","PA"], 2)将找到两个匹配项(NJ 和 PA)并因此返回 4。

def similarity_points(attr_1, attr_2, points)
    """Award a number of points for each shared attribute.

    attr_1 and attr_2 should be lists to compare. 
    """
    number_shared = len(set(attr_1) & set(attr_2))
    return number_shared * points

然后,您可以像这样调用上面的代码:

wilduck_jmitchel3_points = check_match("Wilduck", "jmitchel3")
于 2013-02-11T22:18:26.957 回答