Python 比较列表值

Python 比较列表值,python,list,Python,List,如何修改此代码以允许我使用last_coordinates列表与当前coordinates列表进行比较,以便在这两个列表之间的值存在差异时调用类似activate()的方法 HOST = '59.191.193.59' PORT = 5555 coordinates = [] def connect(): globals()['client_socket'] = socket.socket(socket.AF_INET, socket.SOCK_STREAM) clie

如何修改此代码以允许我使用
last_coordinates
列表与当前
coordinates
列表进行比较,以便在这两个列表之间的值存在差异时调用类似
activate()
的方法

HOST = '59.191.193.59'
PORT = 5555

coordinates = []

def connect():   
    globals()['client_socket'] = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_socket.connect((HOST,PORT))

def update_coordinates():
    screen_width = 0
    screen_height = 0
    while True:
        try:
            client_socket.send("loc\n")
            data = client_socket.recv(8192)
        except:
            connect();
            continue;

        globals()['coordinates'] = data.split()

        if(not(coordinates[-1] == "eom" and coordinates[0] == "start")):
            continue

        if (screen_width != int(coordinates[2])):
        screen_width = int(coordinates[2])
                screen_height = int(coordinates[3])
        return

Thread(target=update_coordinates).start()
connect()
update_coordinates()
while True:
    #compare new and previous coordinates then activate method?
    activate()

您需要在模块范围内初始化最后的_坐标

last_coordinates = ['start', 0, 0]
收到数据后,添加类似以下代码的内容:

globals()['coordinates'] = data.split()
if last_coordinates[0] != coordinates[0] or \
   last_coordinates[1] != coordinates[1] or \
   last_coordinates[2] != coordinates[2]:
   # Do something useful here

# this line copies your coordinates into last_coordinates
last_coordinates = coordinates[:]
正如其他人在评论中指出的那样,您的代码还存在其他问题。例如,上述片段中的第一行最好重写为:

 global coordinates
 coordinates = data.split()

但是,您可能仍然存在线程问题。

网络/套接字代码与此问题有什么关系?您使用
globals()
的任何特定原因?在分配给它之前,请使用
globals坐标,而不是
globals()['coordinates']
,或者使用
坐标[:]=data.split()
以完全避免本地与全局分配问题。您的代码中没有
最后一个坐标列表。@Edward:您运行的是线程吗?!访问全局列表时,您将遇到更多问题。在任何情况下,
globals()
都不会保护您免受这些问题的影响,并且与使用
global坐标
不会有任何不同。