2012-04-01 99 views
3

我有一個Python腳本,每5秒查詢一次MySQL數據庫,收集最新的三個ID的幫助臺票據。我使用MySQLdb作爲我的驅動程序。但問題是在我的「while」循環中,當我檢查兩個數組是否相等時。如果不相等,我會打印「新票已到。」但是這絕不會打印!見我的代碼:Python「While」循環邏輯錯誤?

import MySQLdb 
import time 

# Connect 
db = MySQLdb.connect(host="MySQL.example.com", user="example", passwd="example", db="helpdesk_db", port=4040) 
cursor = db.cursor() 

IDarray = ([0,0,0]) 
IDarray_prev = ([0,0,0]) 

cursor.execute("SELECT id FROM Tickets ORDER BY id DESC limit 3;") 
numrows = int(cursor.rowcount) 
for x in range(0,numrows): 
    row = cursor.fetchone() 
    for num in row: 
     IDarray_prev[x] = int(num) 
cursor.close() 
db.commit() 

while 1: 
    cursor = db.cursor() 
    cursor.execute("SELECT id FROM Tickets ORDER BY id DESC limit 3;") 

    numrows = int(cursor.rowcount) 
    for x in range(0,numrows): 
     row = cursor.fetchone() 
     for num in row: 
     IDarray[x] = int(num) 

    print IDarray_prev, " --> ", IDarray 
    if(IDarray != IDarray_prev): 
     print "A new ticket has arrived." 

    time.sleep(5) 
    IDarray_prev = IDarray 
    cursor.close() 
    db.commit() 

現在,當這個跑了,然後我創建了一個新的機票,輸出看起來是這樣的:

[11474, 11473, 11472] --> [11474, 11473, 11472] 
[11474, 11473, 11472] --> [11474, 11473, 11472] 
[11474, 11473, 11472] --> [11474, 11473, 11472] 
[11474, 11473, 11472] --> [11474, 11473, 11472] 
[11475, 11474, 11473] --> [11475, 11474, 11473] 
[11475, 11474, 11473] --> [11475, 11474, 11473] 
[11475, 11474, 11473] --> [11475, 11474, 11473] 
[11475, 11474, 11473] --> [11475, 11474, 11473] 
[11475, 11474, 11473] --> [11475, 11474, 11473] 

凡我輸出的格式是:

[Previous_Last_Ticket, Prev_2nd_to_last, Prev_3rd] --> [Current_Last, 2nd-to-last, 3rd] 

注意數量的變化,更重要的是,缺少「新票已經抵達」!

回答

7

的問題是以下行:

IDarray_prev = IDarray 

在Python,這使得IDarray_prev相同基礎列表作爲IDarray。其中一項的變化將反映在另一項中,因爲它們都指向相同的東西。

爲了使您可以使用後比較列表的副本,嘗試:

IDarray_prev = IDarray[:] 

[:]是Python的切片標誌,意思是「整個列表的副本」。

+0

美麗!就是這樣!謝謝! – armani 2012-04-01 20:30:52

+2

或者你可以在'copy'模塊中使用'copy'功能。 – 2012-04-01 20:31:48

+1

是的,有很多方法可以解決這個問題。你可以使用'copy',或者你也可以使用'list(IDarray)'。 – 2012-04-01 20:32:31

2

Python與引用一起工作,因此基本上在迭代第一次後更改這兩個列表(因爲在將IDarray指定爲IDarray_prev之後它們都具有相同的引用)。

嘗試使用IDArray_prev = list(IDarray)指定IDarray的副本。

+0

修復了您的代碼格式。請注意內聯代碼的反引號以及代碼塊的四位縮進。感謝您的貢獻! – 2012-04-01 20:53:39

+0

感謝您的編輯和反饋。 – Mihai 2012-04-01 21:50:11