帮我用python写个代码,使其读取文本文件中的数据并分别统计总人次、男/女人数、男/女RBC平均和WBC平均7个统计指标以及各有效检查次数的人数;按升序输出检查次数最多的人员编号实际文件中表头占1行(制表符'\t'分隔的6列), 第2行是所有的数据记录, 记录内部和记录之间都用制表符'\t'分隔。患者ID长度为固定长度7位,以字符“Z”开头,数字部分为6位,不足位数补0
时间: 2023-06-11 15:09:07 浏览: 185
下面是一个示例代码,其中假设数据文件名为"data.txt",文件中的数据用制表符分隔,每行数据的顺序为:患者ID、性别、RBC计数、WBC计数、检查次数。
```python
# 定义要统计的指标
total_count = 0
male_count = 0
female_count = 0
male_rbc_avg = 0
female_rbc_avg = 0
male_wbc_avg = 0
female_wbc_avg = 0
check_count_dict = {}
# 打开文件并读取数据
with open("data.txt", "r") as f:
f.readline() # 跳过表头
for line in f:
data = line.strip().split("\t")
patient_id = data[0]
gender = data[1]
rbc_count = float(data[2])
wbc_count = float(data[3])
check_count = int(data[4])
# 统计指标
total_count += 1
if gender == "M":
male_count += 1
male_rbc_avg = (male_rbc_avg * (male_count - 1) + rbc_count) / male_count
male_wbc_avg = (male_wbc_avg * (male_count - 1) + wbc_count) / male_count
elif gender == "F":
female_count += 1
female_rbc_avg = (female_rbc_avg * (female_count - 1) + rbc_count) / female_count
female_wbc_avg = (female_wbc_avg * (female_count - 1) + wbc_count) / female_count
if check_count in check_count_dict:
check_count_dict[check_count] += 1
else:
check_count_dict[check_count] = 1
# 输出统计结果
print("Total count: ", total_count)
print("Male count: ", male_count)
print("Female count: ", female_count)
print("Male RBC avg: ", male_rbc_avg)
print("Female RBC avg: ", female_rbc_avg)
print("Male WBC avg: ", male_wbc_avg)
print("Female WBC avg: ", female_wbc_avg)
print("Check count distribution:")
for check_count in sorted(check_count_dict.keys()):
print(check_count, ": ", check_count_dict[check_count])
# 按升序输出检查次数最多的人员编号
with open("data.txt", "r") as f:
f.readline() # 跳过表头
data_list = []
for line in f:
data = line.strip().split("\t")
patient_id = data[0]
check_count = int(data[4])
data_list.append((patient_id, check_count))
sorted_data = sorted(data_list, key=lambda x: x[1], reverse=True)
print("Patient ID with most check count in ascending order:")
for data in sorted_data:
print("Z{:06d}".format(int(data[0][1:])))
```
阅读全文