从字典行到页面

👁️ 2 人浏览 💬 0 人评论 ❤️ 添加收藏

(这一节留言不再是一串字符串,而是一列字典:{"id": 编号, "text": 内容, "by": 作者};数据存在一个 JSON 文件里,应用启动时读、改动后写回——project_06 会把它换成数据库。)

ROWS = [{"id": 1, "text": "第一条留言", "by": "小明"}, {"id": 2, "text": "今天天气不错", "by": "小红"}, {"id": 3, "text": "天气预报说明天下雨", "by": "小明"}, {"id": 4, "text": "不许", "by": "路人"}]

按作者筛、按关键字搜,再渲成 li 数一数:

import html
ROWS = [{"id": 1, "text": "第一条留言", "by": "小明"}, {"id": 2, "text": "今天天气不错", "by": "小红"}, {"id": 3, "text": "天气预报说明天下雨", "by": "小明"}, {"id": 4, "text": "<b>不许</b>", "by": "路人"}]

def search(rows, q="", by=""):
    out = []
    for r in rows:
        if q and q not in r["text"]:
            continue
        if by and r["by"] != by:
            continue
        out.append(r)
    return out


def rows_html(rows):
    return "".join("<li>" + html.escape(r["text"]) + " —— " + html.escape(r["by"]) + "</li>" for r in rows)

print(str(len(search(ROWS, q="天气"))) + "/" + str(len(search(ROWS, by="小明"))) + "/" + str(len(search(ROWS, q="天气", by="小明"))) + "/" + str(rows_html(search(ROWS, by="路人")).count("&lt;")))
提交你的答案
请登录后提交答案。
去登录
代码编辑器
Ctrl + Enter 运行
本次输入:
输出:

                        
👩‍🏫
AI
💬 题目评论

全部评论