【问题标题】:how to find something from a list in a text file如何从文本文件的列表中查找内容
【发布时间】:2015-04-23 18:09:02
【问题描述】:
with open ("patientlist.txt","r") as file:
    patientlist = [line.split(",")for line in file]
for patient in patientlist:
    patient[-1] = patient[-1].replace('\n',"")

def medicine():
    health=input("choose the medicine you want to display clients for")
    vMember=False
    while vMember==False:
        for m in patientlist:
            if m[0] == health:
                vMember=True

从这里,我可以添加什么,以便从文本文件 (patientlist) 中的列表中显示使用“吸入器”的每个人,并在另一列中显示他们的年龄,例如,

paul,50,antidepressants
liz,24,inhaler
jack,30,epipen

【问题讨论】:

  • 您的代码有语法错误。患者列表在哪里定义?您能否显示一些用于解析信息的文本文件的格式?
  • 给定inhaler 的输入,您想显示与其相关的所有信息吗?比如跟它关联的名字,然后是那些人的信息?
  • 打开 ("patientlist.txt","r") 作为文件:patientlist=[line.split(",")for line in file] 患者列表中的患者:client[-1] =client[-1].replace('\n',"")
  • 编辑您的问题以包含文本文件的示例。

标签: python arrays python-3.x


【解决方案1】:

遍历列表并显示(使用)该记录。无需使用变量 vMember。以您的方式使用 vMember 将在患者第一次使用“吸入器”时停止迭代。

def medicine():
    health=input("choose the medicine you want to display clients for")
    for m in patientlist:
        if m[2] == health:    # Note, change of m[0](name) to m[2](health)
            print m

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多