【发布时间】:2019-06-25 10:20:07
【问题描述】:
我试图通过取出所有类型为 None 的条目来过滤 Python 中的列表,但是当我尝试这样做时,我收到错误“TypeError: 'NoneType' object is not iterable”。我看不出哪里出错了。
原来的错误实际上是与该行一起出现的 如果 u"Restaurants" 不营业[u"categories"]: 我遇到与之前相同的错误,所以我尝试过滤几行以避免它,但我遇到了同样的问题
这是完整的代码块,尽管错误消息来自过滤器函数
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 组成,其中包含许多看起来像这样的条目。有些类别只是在其中包含“无”,这似乎是问题所在。
{"business_id":"1SWheh84yJXfytovILXOAQ","name":"Arizona Biltmore Golf Club","address":"2818 E Camino Acequia Drive","city":"Phoenix","state":"AZ" ,"postal_code":"85016","latitude":33.5221425,"longitude":-112.0184807,"stars":3.0,"review_count":5,"is_open":0,"attributes":{"GoodForKids":" False"},"categories":"Golf, Active Life","hours":null}
代码应该在 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
【问题讨论】:
-
@DeveshKumarSingh 有时最好在发布之前检查一下假设...
d = {"foo": 42}; print(d[u"foo"]) -
我在业务["categories"] 中遇到同样的错误