2017-05-30 77 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'中? (是的,我已經知道答案,但未來的訪問者將無法從您的帖子中獲取該信息)。 –