我试图通过取出所有类型为None的条目来过滤Python中的列表,但是当我尝试这样做时,出现错误'TypeError:'NoneType'对象不可迭代。我看不到我要去哪里了。
原始错误实际上是与该行一起出现的 如果您的“餐馆”不营业[u”类别”]: 我在哪里遇到了与先前相同的错误,因此我尝试过滤掉几行以避免发生这种情况,但遇到了同样的问题
这是完整的代码块,尽管错误消息来自过滤器功能
import json
restaurant_ids = set()
# open the businesses file
with codecs.open(businesses_filepath, encoding='utf_8') as f:
# iterate through each line (json record) in the file
for business_json in f:
# convert the json record to a Python dict
business = json.loads(business_json)
business[u"categories"] = filter(lambda a: a is not None, business[u"categories"])
print business[u"categories"]
# if this business is not a restaurant, skip to the next one
if u"Restaurants" not in business[u"categories"]:
continue
# add the restaurant business id to our restaurant_ids set
restaurant_ids.add(business[u'business_id'])
# turn restaurant_ids into a frozenset, as we don't need to change it anymore
restaurant_ids = frozenset(restaurant_ids)
# print the number of unique restaurant ids in the dataset
print '{:,}'.format(len(restaurant_ids)), u'restaurants in the dataset.'
我要过滤的文件包含一个JSON,其中包含许多看起来像这样的条目。有些类别中根本没有“ None”,这似乎是问题所在。
{“ business_id”:“ 1SWheh84yJXfytovILXOAQ”,“名称”:“ Arizona Biltmore Golf Club”,“地址”:“ 2818 E Camino Acequia Drive”,“ city”:“ Phoenix”,“ state”:“ AZ” ,“邮政编码”:“ 85016”,“纬度”:33.5221425,“经度”:-112.0184807,“星星”:3.0,“评论计数”:5,“ is_open”:0,“属性”:{“ GoodForKids”:“ False“},”类别“:”高尔夫,活跃生活“,”小时“:空}
该代码应在if语句之后删除所有非“餐厅”类别,但我似乎甚至无法进入该阶段。
它引发错误
TypeError Traceback (most recent call last)
<ipython-input-84-ac1362de4f26> in <module>()
11 business = json.loads(business_json)
12
---> 13 business[u"categories"] = filter(lambda a: a is not None, business[u"categories"])
14 # print business[u"categories"]
15
TypeError: 'NoneType' object is not iterable
答案 0 :(得分:0)
此:
filter(lambda a: a is not None, business[u"categories"])
尝试从None
中删除所有business["categories"]
的出现-假定business["categories"]
是可迭代的。如果它是None
(只是一个None
,而不是包含None
的列表),则确实会引发以下确切错误:
business = {"categories": None}
filter(lambda a: a is not None, business[u"categories"])
您要在此处测试business[u"categories"]
是否 None
,而不是是否包含 None
。
使用codecs.open(businesses_filepath,encoding ='utf_8')作为f:
# iterate through each line (json record) in the file
for business_json in f:
business = json.loads(business_json)
categories = business[u"categories"]
if categories is None:
# if it's None it cannot contain "Restaurant" obviously
continue
if u"Restaurants" not in categories:
continue
# ok it's a restaurant
答案 1 :(得分:-1)
当获得null(None)值时会产生Nonetype错误,因此首先打印(业务)并在终端中显示它是否打印了任何内容?进一步移动另一行。我认为 json.loads(business_json)不会返回任何内容。您应该尝试 json.load(business_json)或 business_json.json ()