我是 python 的初学者,不允许导入外部模块来帮助我的工作,而且我在使用列表索引时遇到了问题。所以,我正在运行几条测试线来解决这个问题(第 8 到 11 行)。注意第10行可以正常输出,反之第11行会报错。此外,第 12 行会引发错误,但第 17 行中的类似代码可以正常工作。
search_keyword = input() # Asks for patient's name or id (either one), if patient's name or id exists in database, output display other details such as Age, Group & Zone.
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('ATO1A')) # 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("Group: " + patient_details[1])
print("Zone: " + patient_details[2])
print("Phone Number: " + patient_details[3])
print("ID: " + patient_details[4]) # no error here, patient_details[4] is able to display patient's id
数据库.txt
NICK,ATO,A,01123381633,ATO1A,POSITIVE,Not Required,Not Required,C1,ACTIVE|MAX,AHS,F,01123361633,AHS2F,NEGATIVE,To Be Determined,To Be Determined,,|JOHN,SID,F,01123331333,SID3F,NEGATIVE,To Be Determined,To Be Determined,,|ZOFIA,AHD,C,01123341633,AHD4C,POSITIVE,Not Required,Not Required,C2,ACTIVE|
第 8,9,10 和 11 行的测试命令:
Line 8: [NICK, ATO, A, 01123381633, ATO1A, POSITIVE, Not Required, Not Required, C1, ACTIVE]
Line 9: 10
Line 10: 4
Line 11: IndexError: list index out of range
有人可以在不使用任何导入模块的情况下解释为什么会发生这种情况,以及有关此问题的任何解决方案吗?感谢您提供任何帮助。