python 属性错误:“dict”对象没有属性“predictors”

pdsfdshx  于 2022-12-17  发布在  Python
关注(0)|答案(3)|浏览(229)

我是python新手,找不到这个问题的答案。参考消息末尾的代码,我能知道下面一行中的“for item,total in totals.items()”是什么意思吗?

rankings = [(total/simSums[item], item) for item, total in totals.items()]

另外,代码失败并显示
属性错误:“dict”对象没有属性“predictors”
当我把代码中“item(s)”的所有示例都改为“predictor(s)"时,为什么会这样呢?

# Return the Pearson correlation coefficient for p1 and p2
def sim_person(prefs, p1, p2):
    # Get the list of shared_items
    si={}
    for item in prefs[p1]:
        if item in prefs[p2]:si[item]=1

    # Find the number of elements 
    n=len(si)

    # if they have no ratings in common, return 0
    if n==0: return 0

    # Add up all the preferences
    sum1 = sum([prefs[p1][it] for it in si])
    sum2 = sum([prefs[p2][it] for it in si])

    # Sum up the squares
    sum1Sq = sum([pow(prefs[p1][it],2) for it in si])
    sum2Sq = sum([pow(prefs[p2][it],2) for it in si])

    # Sum up the products
    pSum = sum([prefs[p1][it]*prefs[p2][it] for it in si])

    # Calculate Person score
    num = pSum - (sum1*sum2/n)
    den = sqrt((sum1Sq - pow(sum1,2)/n)*(sum2Sq - pow(sum2,2)/n))
    if den == 0: return 0

    r = num/den
    return r

# Returns the best matches for person from the prefs dictionary.
# Number of results and similarity function are optional params.
def topMatch(prefs, person, n=5, similarity=sim_person):
    scores = [(similarity(prefs, person, other), other) 
              for other in prefs if other!=person]

    # Sort the list so the highest scores appear at the top
    scores.sort()
    scores.reverse()
    return scores[0:n]

# Gets recommendations for a person by using a weighted average
# of every other user's rankings 
def getRecommendations(prefs, person, similarity=sim_person):
    totals = {}
    simSums = {}
    for other in prefs:
        # don't compare me to myself
        if other == person: continue
        sim = similarity(prefs, person, other)

        # ignore scores of zero of lower
        if sim<=0: continue
        for item in prefs[other]:

            # only score movies I haven't seen yet
            if item not in prefs[person] or prefs[person][item]==0:
                # Similarity * Score
                totals.setdefault(item, 0)
                totals[item]+=prefs[other][item]*sim
                # Sum of similarities
                simSums.setdefault(item, 0)
                simSums[item]+=sim

    # Create the normalized list 
    rankings = [(total/simSums[item], item) for item, total in totals.items()]

    # Return the sorted list 
    rankings.sort()
    rankings.reverse()
    return rankings
y1aodyip

y1aodyip1#

尝试不使用点符号,如下所示:

sample_dict = {'name': 'John', 'age': 29}
print(sample_dict['name']) # John
print(sample_dict['age'])  # 29
mdfafbf1

mdfafbf12#

dict.items迭代字典中的键-值对,因此for key, value in dictionary.items()将循环遍历每一对,这是文档信息,你可以在官方网页上查看,或者更简单,打开python控制台输入help(dict.items),现在,作为一个例子:

>>> d = {'hello': 34, 'world': 2999}
>>> for key, value in d.items():
...   print key, value
...
world 2999
hello 34

AttributeError是一个异常,当一个对象没有你试图访问的属性时抛出。类dict没有任何predictors属性(现在你知道在哪里检查它:)),因此当你试图访问它时它会抱怨。

ojsjcaue

ojsjcaue3#

product_details = {
  'name':'mobile',
  'company':'samsung'
}

访问product_details.name将抛出错误dict object has no attribute 'name'
原因是我们使用点(.)访问dict项,正确的方法是这样的:

product_details['name']

在python中我们使用点操作符来访问对象的值。
dictionary.items()允许我们循环字典中的键:值对

for key, value in product_details.items(): 
    print(key,':',value)

对于循环的每一次迭代,一个key和它的值被赋给变量key和value,这就是items()方法的工作原理。

相关问题