我正在写一些应该解析CSV文件的Python代码。计算特定行的平均值,然后根据CSV文件中的一行值向收件人发送电子邮件。我的代码如下,我已删除了电子邮件的发送,现在的代码和一个print语句替换它:For循环字典不工作后执行列表理解
def main():
#smtp_instance = smtplib.SMTP('localhost')
ldap_file = open('ldaps.csv','rU')
ldap_data=csv.DictReader(ldap_file)
scores = list(int(d['score']) for d in ldap_data)
average_score = sum(scores)/len(scores)
print average_score
for rows in ldap_data:
ldap = rows['ldap']
fullname = rows['fullname']
firstname = fullname.split(' ')[0]
location = rows['location']
score = rows['score']
if int(score) < average_score:
score_msg = 'below'
else:
score_msg = 'above'
print 'Hi ' + firstname + '\n'\
'You got a ' + score + '% on your Final Exam.'\
'The average score was ' + average_score + '.'\
'This means that you scored ' + score_msg + ' average.'
if __name__ == '__main__':
main()
当我运行这个它打印AVERAGE_SCORE值。但代码从来没有得到for..loop。似乎我不能在dict上调用列表理解,然后在同一个dict上迭代。任何想法我做错了,我该如何解决它?
尝试只打印'ldap_data'之前和之后的理解,如果你认为它是受到损坏。或者用'pdb'遍历它并检查相同的东西。 – Useless 2012-01-09 13:29:36