1 Commits

Author SHA1 Message Date
zrzz-maker 65c15a0971 更新 written.md 2026-10-06 20:01:01 +08:00
3 changed files with 33 additions and 58 deletions
-44
View File
@@ -1,44 +0,0 @@
import json
import os
def analyze_log(filepath):
d={
"total":0,
"by_level":{},
"by_user":{},
"last_error":None
}
if not os.path.exists(filepath):
return d
try:
f=open(filepath,'r',encoding='utf-8')
lines=f.readlines()
except:
return d
for line in lines:
line = line.strip()
if line =="":
continue
try:
data = json.loads(line)
except:
continue
d["total"]+=1
lvl=data["level"]
usr=data["user"]
if lvl not in d["by_level"]:
d["by_level"][lvl]=0
d["by_level"][lvl]=d["by_level"][lvl]+1
if usr not in d["by_user"]:
d["by_user"][usr]=0
d["by_user"][usr]=d["by_user"][usr]+1
if lvl == "ERROR":
d["last_error"]=data["message"]
f.close()
return d
-13
View File
@@ -1,13 +0,0 @@
from main import analyze_log
f = open("app.jsonl","w",encoding="utf-8")
f.write('{"timestamp": "2026-10-01 10:23:45", "level": "INFO", "message": "用户登录成功", "user": "张三"}\n')
f.write('{"timestamp": "2026-10-01 10:24:01", "level": "ERROR", "message": "数据库连接失败", "user": "李四"}\n')
f.write('随便写的\n')
f.write('{"timestamp": "2026-10-01 10:27:00", "level": "INFO", "message": "任务完成", "user": "王五"}\n')
f.close()
res=analyze_log("app.jsonl")
print("总数:",res["total"])
print("级别统计:",res["by_level"])
print("用户统计",res["by_user"])
print("最后一条错误:",res["last_error"])
+33 -1
View File
@@ -163,7 +163,7 @@
### 答案
(在此填写,格式:`1. A 2. B 3. C 4. D 5. A 6. B 7. C 8. D 9. A 10. B`)
(在此填写,格式:`1. B 2. B 3. B 4. B 5. B 6. B 7. B 8. B 9. B 10. B`)
---
@@ -183,6 +183,9 @@ c = copy.deepcopy(a)
```
(在此作答)
a、b、c三者的关系:a是原始嵌套列表,b是用a.copy()做的浅拷贝,c是用copy.deepcopy(a)做的深拷贝。
执行a[0].append(99)之后,b会变成[[1, 2, 99], [3, 4]],因为b是浅拷贝,b里的子列表会跟着a的变化而变化。
c还是[[1, 2], [3, 4]],因为深拷贝把内层的子列表也都复制了新的,和a完全没关系了,所以a的修改不会影响到c
### 第 2 题:字典与列表的综合应用
@@ -203,6 +206,23 @@ logs = [
3. 解释为什么第 2 问不能直接用 `len(logs)` 得到结果,需要什么遍历结构?
(在此作答)
m=[]
for i in logs:
n=i["level"]
if n=="ERROR":
m.append(i)
d={}
for i in logs:
u=i["user"]
if u in d:
d[u]=d[u]+1
else:
d[u]=1
因为 len(logs) 算出来的是总共有5条字典,没法知道每个人到底出现了几次。
得用 for 循环遍历 logs 列表,取出里面的 user 名字,同一个人就在原来数字上加一,最终知道这个人出现几次
### 第 3 题:异常处理设计
@@ -218,3 +238,15 @@ Day_10 中你写过 `safe_int(s)` 函数:能转就返回整数,不能转就
请写出函数代码,并说明:为什么这里用 `try/except` 比先用 `if` 判断再计算更好?
(在此作答)
def safe_divide(a,b)
try:
x=float(a)
y=float(b)
m=x/y
return m
except ValueError:
return None
except ZeroDivisionError:
return None
因为用if要先判断字符串有没有转换成数字,而且分母不能为0,很麻烦;但是用try/except就很方便了,直接运行去算,算错了还会有None输出