Reading data in lists: Error
Peter Otten
__peter__ at web.de
Sat Feb 28 05:49:19 EST 2004
> I ran this code only to get the following error:
>
> File "<string>", line 24
> NYA=x[i]-x[i-1]
> ^
> SyntaxError: invalid syntax
>
>
> I remember Mr.Skip Montanaro quoting in his email earlier that at the
> point I make the assignment neither x has no i'th elements. I am sure this
> is what is happening now.
How can you be sure when Python reports a SyntaxError?
> Can someone advise any possible work around to this problem ??
See Paul McGuire's post for a fix. As a general rule, you should break messy
expressions into small chunks that are easier to maintain. In your code you
could introduce a distance(x0, y0, x1, y1) function and test it separately
from the rest. Here's another approach that might be helpful if you are
familiar with complex numbers - yes, Python has them built in :-)
# assuming pres, x, y as in your post
FZ = []
# you should create the complex numbers directly in the for loop
# reading from the file - I'm just lazy
z = [complex(x0, y0) for x0, y0 in zip(x, y)]
for z0, z1, p in zip(z, z[1:], pres):
d = z1-z0
FZ.append(p*d/abs(d))
# assuming you accidentally swapped FX and FY
FX = [z.real for z in FZ]
FY = [-z.imag for z in FZ] # not sure about the sign
If you're confused by the zip trick in the for loop, here's how it works in
three simple steps:
>>> a = ["a", "b", "c"]
>>> b = ["x", "y", "z"]
>>> zip(a, b)
[('a', 'x'), ('b', 'y'), ('c', 'z')]
zip() will end, when the shortest list is exhausted:
>>> b[1:]
['y', 'z']
>>> zip(a, b[1:])
[('a', 'y'), ('b', 'z')]
>>> zip(a, a[1:])
[('a', 'b'), ('b', 'c')]
I. e, zip(alist, alist[1:]) will create a list of all adjacent pairs in
alist.
Peter
More information about the Python-list
mailing list