2017-05-30 80 views
-1
paid_students=[] 
for students in enrollments: 
    if students['days_to_cancel']==None or students['days_to_cancel']>7: 
     paid_students.append(students) 
print len(paid_students) 

输出:为什么所有的数据越来越附加到列表

1640 

len(enrollments)的价值也1640。为什么所有行都会附加到paid_studentslist后面,即使注册中有很多行具有宽范围的['days_to_cancel']值。

的入学

实例数据
{u'account_key': u'448', 
u'cancel_date': u'2014-11-10', 
u'days_to_cancel': u'5', 
u'is_canceled': u'True', 
u'is_udacity': u'True', 
u'join_date': u'2014-11-05', 
u'status': u'canceled'} 

{u'account_key': u'448', 
u'cancel_date': u'2015-01-27', 
u'days_to_cancel': u'0', 
u'is_canceled': u'True', 
u'is_udacity': u'True', 
u'join_date': u'2015-01-27', 
u'status': u'canceled'} 

来源,Udacity

+0

检查代码中的“> 7”是否正确? –

+0

@AshKetchum是在问题中询问'days_to_cancel'必须大于7. –

+3

您正将* strings *与一个整数进行比较。在Python 2中,'u''> 7'总是如此,因为数字总是在其他对象类型之前排序。将该值转换为一个整数* first *。 –

回答

0

这个工作对我来说:我的第二个参数中添加一个int()如果, 你比较蜇伤(你的DIC值)整数,在python 2中,如评论中指出的,总是返回true。

enrollments= [{u'account_key': u'448', u'cancel_date': u'2014-11-10', u'days_to_cancel': u'5', u'is_canceled': u'True', u'is_udacity': u'True', u'join_date': u'2014-11-05', u'status': u'canceled'}, 
{u'account_key': u'448', u'cancel_date': u'2015-01-27', u'days_to_cancel': u'10', u'is_canceled': u'True', u'is_udacity': u'True', u'join_date': u'2015-01-27', u'status': u'canceled'}] 

paid_students=[] 
for students in enrollments: 
    if students['days_to_cancel']==None or int(students['days_to_cancel'])>7: 
     paid_students.append(students) 

print len(paid_students) 
+1

解释你改变了什么以及为什么。没有解释,这不是一个有用的答案。 –

+0

@MartijnPieters新增 –

+1

所以*为什么*你添加了'int()'?为什么它会将所有元素都添加到'paid_students'中? (是的,我已经知道答案,但未来的访问者将无法从您的帖子中获取该信息)。 –