我的python代码有什么错误?

时间:2013-11-25 00:33:40

标签: 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_name:date:location

使用上面的我想得到

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

其他人(日期,地点)相同,我如何修复我的代码,这是我的结果

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

1 个答案:

答案 0 :(得分:3)

或者

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()