Paul Z wrote: > Hi, > > I writed some codes as the UDP messages: > > import socket > import random > from array import * > > port = 8088 > host = "localhost" > > s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) > > num = array('f') > x = 0 > while x < 6: > num.append(random.random()) > x += 1 > > a0 = str("%.2f"%num[0]) + ',' > a1 = str("%.2f"%num[1]) + ',' > a2 = str("%.2f"%num[2]) + ',' > a3 = str("%.2f"%num[3]) + ',' > a4 = str("%.2f"%num[4]) + ',' > a5 = str("%.2f"%num[5]) + ',' > > msg1 = 'a,' + a0 + a1 + a2 > msg1 = bytes(msg1, 'utf-8') > msg2 = 'b,' + a3 + a4 + a5 > msg2 = bytes(msg2, 'utf-8') > > s.sendto(msg1, (host, port)) > s.sendto(msg2, (host, port)) > > and I receive the messages via: > > import socket > port = 8088 > s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) > s.bind(("",port)) > print('waiting on port:',port) > while True: > data,addr = s.recvfrom(1024) > print('reciveed:', data, "from", addr) > > I want to arrange the messages to: > > array1 = #the numbers which is start as 'a' in the messages > array2 = #the numbers which is start as b in the messages
You can put the lists into a dict. Then lists["a"] accesses one and lists["b"] accesses the other list. items1 = [] items2 = [] lists = {"a": items1, "b": items2} while True: data, addr = s.recvfrom(1024) print('received:', data, "from", addr) parts = data.decode("utf-8").split(",") key = parts.pop(0) lists[key].extend(float(p) for p in parts if p.strip()) print("items1:", items1) print("items2:", items2) You can extend this approach to an arbitrary number of lists if you add them dynamically to the dict: lists = {} while True: ... parts = ... key = parts.pop(0) if key not in lists: lists[key] = [] lists[key].extend(...) _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor