Po-jui Chu
Po-jui Chu

Reputation: 1

Python too many values to unpack

so I want to find distance between two xyz file coordinate using python, I was given this for example 0.215822, -1.395942, -1.976109 0.648518, -0.493053, -2.101929 In python, I wrote,

f = open('First_Ten_phenolMeNH3+.txt', 'r')
lines = f.readlines()
a = lines[0] #(0.215822, -1.395942, -1.976109)
(x1,y1,z1) = a
b = lines[1] #(0.648518, -0.493053, -2.101929)
(x2,y2,z2) = b

distance = math.sqrt((x1-x2)**2 + (y1-y2)**2 + (z1-z2)**2)
print(distance)


f.close()

I want to use tuple unpacking and to calucalte distance, however, I keep getting too many values to unpack (expected 3), I think it is because of the txt file, Is there any better way I can do it ?? The problem is i need have 5000 coordinate file to sort through, so it will be inefficient to plug in coordinate one by one.

Thank you

Upvotes: 0

Views: 68

Answers (3)

luigigi
luigigi

Reputation: 4215

You could use this:

from scipy.spatial import distance
from ast import literal_eval
a = literal_eval(lines[0]) #(0.215822, -1.395942, -1.976109)
b = literal_eval(lines[1]) #(0.648518, -0.493053, -2.101929)
dst = distance.euclidean(a, b) #1.009091198622305

Upvotes: 1

Michail Highkhan
Michail Highkhan

Reputation: 567

line[0] is a string, as it in a text file. You need to convert it into tuple of floats

x1, y1, z1 = (float(value) for value in line[1:-1].split(', '))

Upvotes: 0

Almog-at-Nailo
Almog-at-Nailo

Reputation: 1182

you are trying to assign a string to a tuple. try using split() first:

a = lines[0].split() #(0.215822, -1.395942, -1.976109)
(x1,y1,z1) = a

also, this will put strings into x1,x2,x3, you need to convert them to float:

x1 = float(x1)
x2 = float(x2)
x3 = float(x3)

Upvotes: 0

Related Questions