469,343 Members | 5,614 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,343 developers. It's quick & easy.

Subtracting units in an array from themselves

I have a list of coordinates and am trying to ouptput the distance between each coordinate into a new list.


End resulst


Thus far my strategy is to use the enumerate function to create a new array offset from the original array, and then subtract them.

Expand|Select|Wrap|Line Numbers
  1. #creates a list called dataList from and external coordinates file
  2. dataList = [[float(s) for s in item.strip().split(",")] for item in open("coordinates.txt").readlines()]
  4. #creates an empty new array
  5. new_array=[]
  7. #enumerates the list
  8. for i,points in enumerate(dataList):
  9.   x,y,z = points
  10.   x2,y2,z2 = dataList[i+1]
  11.   new_array.append((x2-x, y2-y, z2-z))
  13. print new_array
I get the following error:
File "C:\Python27\coordinate scheme.py", line 9, in <module>
x2,y2,z2 = dataList[i+1]
IndexError: list index out of range

I'm new at Python and especially workining with nested lists and am stuck on where to go from here.
Can you make recommendations on how to address this? Not really sure what list index out of range refers too.
Jun 29 '11 #1
1 1898
2,851 Expert Mod 2GB
It appears that you have a list of lists, and each sublist has 3 elements of type float. If you use enumerate, each sublist is processed from the first to the very last. When the last sublist is processed and you attempt to extract the next element which does not exist (dataList[i+1]), you will receive the index error. You can use range(len(dataList)-1), add a try/except block, etc. to get around the error.
Jun 29 '11 #2

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

5 posts views Thread by Grant Austin | last post: by
7 posts views Thread by Netocrat | last post: by
2 posts views Thread by Russ | last post: by
3 posts views Thread by Martin Joergensen | last post: by
7 posts views Thread by heddy | last post: by
3 posts views Thread by assgar | last post: by
4 posts views Thread by assgar | last post: by
1 post views Thread by assgar | last post: by
reply views Thread by zhoujie | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.