我有一个问题,我有一个打开和关闭业务的json文件。我需要指定开放业务的数量,这就是我这样做的原因。但是它返回“ none”。请注意,我必须使用函数。另外,我没有使用简单的计数器,因为我必须删除已关闭的业务,因为我必须对它们做更多的事情。这不是重复的,因为我尝试了其他帖子所说的,它给了我0。
这是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
}
liste_businesses=[]
liste_open=[]
def number_entries(liste_businesses):
with open ('yelp.txt') as file:
for line in file:
liste_businesses.append(json.loads((line)))
return (len(liste_businesses))
def number_open(liste_businesses):
for e in range (len(liste_businesses)):
if 'is_open' not in liste[e]:
liste_open=liste_businesses.remove(liste[e])
if int(liste[e]['is_open'])==int(0):
liste_open=liste_businesses.remove(liste[e])
print(number_open(liste_businesses))```
答案 0 :(得分:1)
除非您要处理内存限制,否则仅遍历您的业务列表并选择开放的业务可能更简单:
def load_businesses():
businesses = []
with open('yelp.txt') as file:
for line in file:
businesses.append(json.loads(line))
# More idiomatic to return a list than to modify global state
return businesses
def get_open_businesses(businesses):
# Make a new list rather than modifying the old one
open_businesses = []
for business in businesses:
if business.get('is_open', '0') != '0':
open_businesses.append(business)
return open_businesses
businesses = load_businesses()
open_businesses = get_open_businesses(businesses)
print(len(open_businesses))
如果您想对开放业务使用列表理解:
[b for b in businesses if b.get('is_open', '0') != '0']