【发布时间】:2020-05-19 07:34:46
【问题描述】:
所以我有多个患者的信息存储在 database.txt 中,我想将文件中的数据检索到一个列表中。
并且系统提示输入患者id,以搜索并显示患者的其他信息,如姓名、年龄、组别和区域。
但是,我从第 12 行收到错误,但第 17 行中的类似语法能够毫无问题地运行。
search_keyword = input() # Asks for patient's name or id (either one)
with open("database.txt", "r") as database:
for data in database:
for patients in data.split('|'):
patient_details = []
for details in patients.split(','):
patient_details.append(details)
print(patient_details) # test
print(len(patient_details) # test
print(patient_details.index('Patient001')) # test
print(patient_details[4]) # test
if search_keyword == patient_details[0] or search_keyword == patient_details[4]: # error occured here, where it says list index out of range.
print("Name: " + patient_details[0])
print("Age: " + patient_details[1])
print("Group: " + patient_details[2])
print("Zone: " + patient_details[3])
print("ID: " + patient_details[4]) # no error here, patient_details[4] is able to display patient's id
数据库.txt
John,18,A,1,Patient001|Nick,20,F,9,Patient002
第 8,9,10 和 11 行的测试命令:
Line 8: [John, 18, A, 1, Patient001]
Line 9: 5
Line 10: 4
Line 11: IndexError: list index out of range
有人可以解释为什么会发生这种情况,以及在不使用任何导入模块的情况下有关此问题的任何解决方案吗?感谢您的帮助。
【问题讨论】:
-
尝试在
if语句之前打印patient_details。您的数据点可能不是您所期望的。 -
感谢您的回复!我通过在 IF 语句之前添加 print(patient_details) 对其进行了测试,结果将是 [John,18,A,1,Patient001],这是我正在寻找的完美列表,索引 [4] 作为患者ID。但我还必须将 IF 语句更改为 search_keyword == patient_details[0],因为 patient_details[4] 会引发错误。
-
我不确定为什么在 IF 语句之前打印出来的列表是完美的,但是在 IF 语句的下一行使用它时会抛出一个索引列表超出范围错误。