Python AttributeError: 'dict' 对象没有属性 'predictors'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35407560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:24:09  来源:igfitidea点击:

AttributeError: 'dict' object has no attribute 'predictors'

python

提问by Mike

I am new to python and couldn't find the answer to this. Referring to the code at the end of the message, can I know what does the part "for item, total in totals.items()" in the line below mean?

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

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

Also, the code failed and said

另外,代码失败并说

AttributeError: 'dict' object has no attribute 'predictors'

AttributeError: 'dict' 对象没有属性 'predictors'

when I changed all instances of "item(s)" in the code to "predictor(s)". Why is that so?

当我将代码中“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

采纳答案by bgusach

The dict.itemsiterates over the key-value pairs of a dictionary. Therefore for key, value in dictionary.items()will loop over each pair. This is documented information and you can check it out in the official web page, or even easier, open a python console and type help(dict.items). And now, just as an example:

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

The AttributeErroris an exception thrown when an object does not have the attribute you tried to access. The class dictdoes not have any predictorsattribute (now you know where to check it :) ), and therefore it complains when you try to access it. As easy as that.

AttributeError是当对象不具有您尝试访问的属性时抛出的异常。该类dict没有任何predictors属性(现在您知道在哪里检查它 :) ),因此当您尝试访问它时它会抱怨。就这么简单。

回答by Shirantha Madusanka

#Try without dot notation
sample_dict = {'name': 'John', 'age': 29}
print(sample_dict['name']) # John
print(sample_dict['age']) # 29