2013-11-25 66 views
1
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 

格式animalid:日期:地點從TXT文件中的數據來回答問題蟒

以上是我保存在名爲animallog2.txt一個txt文件中的數據。我已經將它導入到我的代碼中了。我想用上面的方法來回答幾個問題。

到目前爲止,這是代碼,我有

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

d = {} 
for animalname, loc in zip(animalnames, locations): 
    d.setdefault(animalname, []).append(loc) 

print("Animal ID","Location1","Location2")  
for k, v in d.items(): 
    print(k, end='\t')      #To print table of the data 
    print(v.count('s1'), end='\t') 
    print(v.count('s2'))   
print("================================================================================================================") 

我已經是表

Animal ID Location1 Location2 
a01  2 1 
a02  0 3 

A03 4 4

可能有人幫助,以我怎麼可以使用所有以上回答的問題:

1)參觀兩站至少4次的動物#answ呃是每個動物的訪問A03

2)總數

回答

2

您已經完成了大部分的工作,這將讓您的答案:

1)

for k, v in d.items(): 
    if v.count('s1')>=4 and v.count('s2')>=4: 
     print k 

2)

for k, v in d.items(): 
    print k, v.count('s1')+v.count('s2')