比较列表值

时间:2012-10-05 08:44:09

标签: 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)
    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()

1 个答案:

答案 0 :(得分:0)

您需要在模块范围

初始化last_coordinates
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()

但是你可能仍然遇到线程问题。