Home > Enterprise >  Fetch separate coordinates from array list
Fetch separate coordinates from array list

Time:01-28

s = ['(2,-1)', '(2,2)']

these are 2 cordinates how can i convert them in this form so that variable x1,x2,y1,y2 contain there value (without using external library)

x1,y1 = 2,-1

x2,y2 = 2,2

I was trying in this way

for i in range(len(s)-1):
    p1 = s[i]
    p2  = s[i 1]
    print p1 ,p2

CodePudding user response:

You could use ast.literal_eval to create a tuple from the string.

from ast import literal_eval
# ...
x1, y1 = literal_eval(s[i])
x2, y2  = literal_eval(s[i 1])
print(x1, y1, x2, y2)

Alternatively, remove the first and last character, split on comma, and convert each part to an int.

def parts(s):
    return map(int, s[1:-1].split(','))
# ...
x1, y1 = parts(s[i])
x2, y2  = parts(s[i 1])

CodePudding user response:

You can use a comprehension to parse your list of strings

# You can replace int by float if needed
x1, y1, x2, y2 = [int(j) for i in s for j in i[1:-1].split(',')]
print(x1, y1)
print(x2, y2)

# Output
2 -1
2 2
  • Related