Python"While"循环逻辑错误?

arm*_*ani 3 python logic while-loop

我有一个Python脚本,每5秒查询一次MySQL数据库,收集帮助台票证的最新三个ID.我使用MySQLdb作为我的驱动程序.但问题是在我的"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()
Run Code Online (Sandbox Code Playgroud)

现在,当这个运行时,我创建了一个新票证,输出如下所示:

[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]
Run Code Online (Sandbox Code Playgroud)

我的输出格式是:

[Previous_Last_Ticket, Prev_2nd_to_last, Prev_3rd] --> [Current_Last, 2nd-to-last, 3rd]
Run Code Online (Sandbox Code Playgroud)

请注意数字的变化,更重要的是,缺少"新票已到达"!

Gre*_*ill 7

问题是以下几行:

IDarray_prev = IDarray
Run Code Online (Sandbox Code Playgroud)

在Python中,这使得IDarray_prev引用相同的基础列表IDarray.一个中的变化将反映在另一个中,因为它们都指向同一个东西.

要制作可用于稍后比较的列表的副本,请尝试:

IDarray_prev = IDarray[:]
Run Code Online (Sandbox Code Playgroud)

[:]是Python切片表示法,意思是"整个列表的副本".

  • 或者你可以在`copy`模块中使用`copy`函数. (2认同)