python - 如何删除某些东西 json 列表?
问题描述
我有这个显示文章的程序,我想添加一个删除文章的选项。底部代码是添加或编辑现有文章内容的选项。我想知道是否使用部分代码来查看是否存在标题以从列表中删除文章。json 列表包含两个对象:标题和内容。因此,在删除标题时,我还想删除其内容。
import json
from bottle import route, run, template, request, redirect, static_file, error
@route('/remove')
articles = read_articles_from_file()
title = getattr(request.forms, "title")
append_flag = True
for i, article in enumerate(articles): #loop through existing articles
if title == article['title']: #if title exists in articles
@route('/update', method="POST")
def update_article():
"""
Receives page title and contents from a form, and creates/updates a
text file for that page.
"""
title = getattr(request.forms, "title")
content = getattr(request.forms, "content")
articles = read_articles_from_file()
append_flag = True
for i, article in enumerate(articles): #loop through existing articles
if title == article['title']: #if new title already exists
articles[i]['content'] = content #update articles content
append_flag = False #update flag to false
break #if title is unique, break loop
if append_flag: #add new post
articles.append({
"title": title.strip(),
"content": content
})
my_file = open("storage/articles.json", "w")
my_file.write(json.dumps(articles, indent=3))
my_file.close()
解决方案
首先找到项目。然后使用list.pop
list docs删除它。像这样:
>>> articles = [{'title': 'one', 'content': 'content_one'}, {'title': 'two', 'content': 'content_two'}]
>>> articles
[{'title': 'one', 'content': 'content_one'}, {'title': 'two', 'content': 'content_two'}]
>>> title_to_remove = 'one'
>>> matching_index = next(i for i, a in enumerate(articles) if a['title'] == title_to_remove)
>>> matching_index
0
>>> articles.pop(matching_index)
{'title': 'one', 'content': 'content_one'}
>>> articles
[{'title': 'two', 'content': 'content_two'}]
推荐阅读
- php - 如何在 jetwoobuilder woocommerce 中添加查询“自定义分类”
- qt - 如何测试一个值是否对 QFlags 有效
- powerbi - 如何删除 Power BI 导出中的白色边框?
- google-cloud-platform - 如何确认 GCP 为 asia-south-1 地区提供的动态 IP 列表是仅属于印度还是其他国家/地区?
- azure-devops - 在组织内的项目之间共享变量组
- python-3.x - 如何查找不同列中存在的组合
- google-sheets - 将两个公式合并到一个单元格中,得到一个结果
- bash - 使用 find+xargs+nohup 将进程置于后台
- sql-server - SQL Server 中的 OBJECT_ID() 在 Snowflake 中是否有任何等价物?
- amazon-web-services - 访问管理控制台时如何生成 AWS SSO url?