gpt4 book ai didi

Python "While"循环逻辑错误?

转载 作者:太空宇宙 更新时间:2023-11-03 12:50:34 27 4
gpt4 key购买 nike

我有一个 Python 脚本,它每 5 秒查询一次 MySQL 数据库,收集最新的三个帮助台工单 ID。我正在使用 MySQLdb 作为我的驱动程序。但问题出在我的“while”循环中,当我检查两个数组是否相等时。如果它们不相等,我打印“A new ticket has arrived”。但这永远不会打印出来!查看我的代码:

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]

请注意数字的变化,更重要的是,没有“新票已到”!

最佳答案

问题出在下面一行:

IDarray_prev = IDarray

在 Python 中,这使得 IDarray_prev 引用与 IDarray 相同 的底层列表。一个的变化会反射(reflect)到另一个,因为它们都指向同一件事。

要制作列表的副本以供稍后比较,请尝试:

IDarray_prev = IDarray[:]

[:] 是 Python 切片符号,表示“整个列表的副本”。

关于Python "While"循环逻辑错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9968006/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com