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_students
list
,即使注册中有很多行的['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 :(得分:0)
这对我有用:我在if的第二个参数中添加了一个int(), 你在比较stings(你的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)