AttributeError:'dict'对象没有属性

Mik*_*ike 22 python

我是python的新手,无法找到答案.参考消息末尾的代码,我可以知道下面一行中的"for item,total in totals.items()"部分是什么意思?

rankings = [(total/simSums[item], item) for item, total in totals.items()]
Run Code Online (Sandbox Code Playgroud)

此外,代码失败并说

# 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
Run Code Online (Sandbox Code Playgroud)

当我将代码中的"item(s)"的所有实例更改为"predictor(s)"时.为什么会这样?

rankings = [(total/simSums[item], item) for item, total in totals.items()]
Run Code Online (Sandbox Code Playgroud)

Shi*_*nka 31

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

  • 对Python新手的解释? (8认同)
  • @joe因为类继承在python中是如何工作的,你正在做'Dict.thing',它试图查找Dict的方法,这不是JS的工作方式,当你添加一个键时它变成一个查找表, (8认同)

bgu*_*ach 21

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
Run Code Online (Sandbox Code Playgroud)

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

  • 非常感谢您指点迷津。我没有意识到totals.items 引用了dict.items,并认为它就像某种JSON 对象。现在我知道将来如何处理此类问题。再次感谢。 (2认同)

小智 15

product_details = {
  'name':'mobile',
  'company':'samsung'
}
Run Code Online (Sandbox Code Playgroud)

访问product_details.name会抛出错误dict object has no attribute 'name'

原因是因为我们使用点( .)来访问字典项。正确的方法是这样的:

product_details['name']
Run Code Online (Sandbox Code Playgroud)

我们使用点运算符来访问 python 中对象的值。

dictionary.items()允许我们循环遍历字典中的键:值对

for key, value in product_details.items(): 
    print(key,':',value)
Run Code Online (Sandbox Code Playgroud)

对于循环的每次迭代,都会将一个键及其值分配给此处的变量 key 和 value。这就是items()方法的工作原理。