change array consist of coordinate(x,y) to string

Viewed 31

i have path planning project with python and the result is array consist of coordinate(x,y) like this:

[(0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (5, 2), (5, 3)]
 

since I want to send that data to arduino to control the movement of the AGV, I have to convert the array above to this format:

{0.1, 1.1, 2.1, 3.1, 4.1, 5.1, 5.2, 5.3}

how to do this with python code???

2 Answers

You can iterate the list and get the rquired float values either by f-string, or by numeric calculation i.e. x+y/10, you can do this in a List Comprehension

# d is the list of tuples that you have in question
>>> [float(f"{x}.{y}") for x,y in d]

[0.1, 1.1, 2.1, 3.1, 4.1, 5.1, 5.2, 5.3]

#or
>>> [x+y/10 for x,y in d]

[0.1, 1.1, 2.1, 3.1, 4.1, 5.1, 5.2, 5.3]

on a side note, the output you have mentioned is set which may not necessarily preserve the order that's why I've created list as final result.

You can use the map function to do this easily. Here in the second line of my code, a lambda function is used to take one item from the num list and convert it to the desired form.

num = [(0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (5, 2), (5, 3)]

float_num = list(map(lambda x: x[0] + x[1] / 10, num))

#printing the results
print(float_num)
Related