Subtracting units in an array from themselves

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Miguel Valenzue
    New Member
    • Dec 2010
    • 39

    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.

    ((x1,y1,z1),(x2 ,y2,z2),...)

    End resulst

    ((x2-x1),(y2-y1),(z2-z1)),...

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

    Code:
    #creates a list called dataList from and external coordinates file
    dataList = [[float(s) for s in item.strip().split(",")] for item in open("coordinates.txt").readlines()]
    
    #creates an empty new array
    new_array=[]
    
    #enumerates the list
    for i,points in enumerate(dataList):
      x,y,z = points
      x2,y2,z2 = dataList[i+1]
      new_array.append((x2-x, y2-y, z2-z))
    
    print new_array
    I get the following error:
    File "C:\Python27\co ordinate 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.
    Thanks
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    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(dataL ist)-1), add a try/except block, etc. to get around the error.

    Comment

    Working...