我的python代码有什么错误?

2024-09-27 20:19:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个密码

animal_names, dates, locations = [], [], []

filename=input("Enter name of file:")
if filename=="animallog1.txt":
    data=open('animallog1.txt','r')
    information=data.read()
    for line in information:
        animal_name, date, location = line.strip().split(':')
        animal_names.append(animal_name)
        dates.append(date)
        locations.append(location)   

    print(animal_names)
    print(dates)
    print(location)

我正在尝试使用txt文件中的数据来打印我想要的结果 txt文件包含以下内容:

a01:01-24-2011:s1 
a03:01-24-2011:s2 
a02:01-24-2011:s2 
a03:02-02-2011:s2 
a03:03-02-2011:s1 
a02:04-19-2011:s2 
a01:05-14-2011:s2 
a02:06-11-2011:s2 
a03:07-12-2011:s1 
a01:08-19-2011:s1 
a03:09-19-2011:s1 
a03:10-19-2011:s2 
a03:11-19-2011:s1 
a03:12-19-2011:s2  

它的格式是动物_姓名:日期:位置

使用上面的我想得到

animal_names=[a01,a02, #till the very end,a03]

对于其余的代码(日期、位置)也是一样的,我如何修复我的代码以使其成为我的结果

我以后还需要用这些列表来回答问题


Tags: nametxtnameslocationfilenamedatesprints2
1条回答
网友
1楼 · 发布于 2024-09-27 20:19:57

或者

def main():
    fname = input("Enter name of file: ")
    with open(fname) as inf:
        names, dates, locations = zip(*[line.strip().split(':') for line in inf])

    print(names)
    print(dates)
    print(locations)

if __name__=="__main__":
    main()

相关问题 更多 >

    热门问题