[Tutor] a beginning question

Alan Gauld alan.gauld at btinternet.com
Sat Feb 20 11:16:56 EST 2016


On 20/02/16 13:23, 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

You could shorten this to:

num = array.array('f',[random.random() for n in range(6)])

> 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')

This is a bit long winded, you could go direct to:

msg1 = bytes('a, %.2f, %.2f, %.2f' % (num[0],num[1],num[2]), 'utf-8')
msg2 = bytes('b, %.2f, %.2f, %.2f' % (num[3],num[4],num[5]), '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

OK, I'm not sure why you are using arrays? Do you have a
reason not to use plain lists? I'm going to assume not
because it keeps things simpler.

[If you need to create an array its easy enough once
you have the lists:
array1 = array.array('f',list1)
]

You first need to split the data by commas:

fields = data.split(',')

Then you need to check the first field for a or b

if fields[0] == 'a':
   list1 = [float(field) for field in field[1:]]
elif fields[0] == 'b':
   list2 = [float(field) for field in field[1:]]
else:
   raise ValueError 'Unknown first field in data'

Another way to do this would be to use a dictionary
based on the first field value:

received = {} # initialise dict
while True:
   data,addr = s.recvfrom(1024)
   fields = data.split(',')
   received[ fields[0] ] = [float(field) for field in field[1:]]

You can then access your data with

value = received['a'][2]  # sets value to 0.7 using your data


hth
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list