Python if语句顺序不同时返回键错误的原因?

Python if语句顺序不同时返回键错误的原因?,python,Python,代码和上下文: 关于数据探索练习的python课程简介。Applestore.csv包含appstore中应用程序的数据,任务是创建一个字典,其中包含年龄等级作为键,频率作为值 opened_file = open('AppleStore.csv') from csv import reader read_file = reader(opened_file) apps_data = list(read_file) content_ratings={} for rows in apps_data[

代码和上下文:

关于数据探索练习的python课程简介。Applestore.csv包含appstore中应用程序的数据,任务是创建一个字典,其中包含年龄等级作为键,频率作为值

opened_file = open('AppleStore.csv')
from csv import reader
read_file = reader(opened_file)
apps_data = list(read_file)
content_ratings={}
for rows in apps_data[1:]:
    c_rating=rows[10]
    if c_rating in content_ratings==false:
        content_ratings.update({c_rating:1})
    else:
        content_ratings[c_rating]+=1
print(content_ratings)
我不明白为什么上面的代码会给我一个关键错误,而下面的代码可以正常工作:

opened_file = open('AppleStore.csv')
from csv import reader
read_file = reader(opened_file)
apps_data = list(read_file)
content_ratings={}
for rows in apps_data[1:]:
    c_ratings=rows[10]
    if c_ratings in content_ratings:
        content_ratings[c_ratings]+=1
    else: 
        content_ratings.update({c_ratings:1})
print(content_ratings)
在上面的例子中,我想我是说,如果c_rating不是作为键出现的,那么更新字典以使键值对为else,只需在值上加1

在第二种情况下,我认为我的意思是,如果密钥已经存在,那么在值中添加1,否则使用密钥-值对更新字典


为什么后者比前者更有效

您的表达式的计算方式为内容评分中的c_评分和内容评分==False。由于第二个条件始终为False,因此整个表达式也始终为False,从而触发else分支的执行,无论c_rating是否在字典中。

您的表达式的计算方式与c_rating in content_ratings和content_ratings==False一样。由于第二个条件始终为False,因此整个表达式也始终为False,从而触发else分支的执行,无论c_rating是否在字典中。

c_rating in content_ratings==False永远不会为true。这些类型的操作符在Python中是连锁的:它相当于content_ratings中的c_ratings和content_ratings==false

你可以写

if (c_rating in content_ratings) == False:
但正确的写作方法是

if c_rating not in content_ratings:
更好的是,你可以用

content_rating[c_rating] = content_rating.get(c_rating, 0) + 1
内容中的c_评级=false永远不会为真。这些类型的操作符在Python中是连锁的:它相当于content_ratings中的c_ratings和content_ratings==false

你可以写

if (c_rating in content_ratings) == False:
但正确的写作方法是

if c_rating not in content_ratings:
更好的是,你可以用

content_rating[c_rating] = content_rating.get(c_rating, 0) + 1
什么是假的?False?内容中的c_评级==False永远不会为真。这些类型的操作符在Python中是连锁的:它在content\u ratings中相当于c\u ratings,content\u ratings==false==false在几乎所有其他语言中通常也是多余的,在Python中它在顶部有一个不明显的含义。什么是false?False?内容中的c_评级==False永远不会为真。这些类型的运算符在Python中是连锁的:它在content\u ratings中相当于c\u ratings,content\u ratings==false==false在几乎所有其他语言中通常也是多余的,在Python中,它在顶部有一个不明显的含义。