gpt4 book ai didi

python - 如何删除字典列表中的元素

转载 作者:行者123 更新时间:2023-12-01 06:53:28 25 4
gpt4 key购买 nike

我遇到一个问题,我有一个打开和关闭的企业的 json 文件。我需要指定开放企业的数量,这就是我这样做的原因。但它返回“无”。请注意,我必须使用函数。另外,我没有使用简单的计数器,因为我必须实际删除已关闭的业务,因为我必须对它们做更多的事情。这不是重复的,因为我尝试了其他帖子所说的内容,它给了我 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
}
import json
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))

最佳答案

除非您正在处理内存限制,否则迭代您的企业列表并选择开放的企业可能会更简单:

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']

关于python - 如何删除字典列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58902503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com