BP.txt是以逗号分隔的时间,血压,心率记录数据文本文件。请找出并打印收缩压【140而心率】75的记录,并统计收缩压的总平均值(保留3位小数),将结果写入到result.txt文件中。
时间: 2023-12-14 19:36:25 浏览: 34
假设BP.txt文件在当前目录下,可以使用以下Python代码实现:
```python
# 打开BP.txt文件
with open('BP.txt', 'r') as f:
records = f.readlines()
sbp_sum = 0 # 收缩压总和
count = 0 # 记录数量
# 遍历记录,查找收缩压为140,心率为75的记录,并计算收缩压总和和记录数量
for record in records:
time, sbp, hr = record.strip().split(',')
if int(sbp) == 140 and int(hr) == 75:
print(record.strip())
sbp_sum += int(sbp)
count += 1
# 计算平均收缩压(保留3位小数)
if count > 0:
avg_sbp = round(sbp_sum / count, 3)
else:
avg_sbp = 0
# 将结果写入result.txt文件
with open('result.txt', 'w') as f:
f.write('收缩压为140,心率为75的记录:\n')
f.writelines([record for record in records if '140,75' in record])
f.write(f'\n收缩压平均值:{avg_sbp}')
```
以上代码会在当前目录下生成result.txt文件,其中包含收缩压为140,心率为75的记录和收缩压平均值。