Search code examples
pythonlistloopscoordinatescoordinate-systems

Change a 2D list based of coordinates


I have a 2D list with placeholder variables to form a coordinate system. I also have a list with different coordinates (a y and x index) and I want to change the corresponding coordinate in the 2D list, and I want to do this for all the coordinates.

Here is the basic code:

coordinate_system = 
[['-'], ['-'], ['-'], ['-'], ['-']]
[['-'], ['-'], ['-'], ['-'], ['-']]
[['-'], ['-'], ['-'], ['-'], ['-']]
[['-'], ['-'], ['-'], ['-'], ['-']]
[['-'], ['-'], ['-'], ['-'], ['-']]
[['-'], ['-'], ['-'], ['-'], ['-']]

coordinates = [[0, 0], [1, 1], [2, 2], [3, 3], [4, 4], [3, 5], [2, 4], [1, 3], [0, 2]]
    

And I somehow want to loop through the coordinates so that I can replace the corresponding coordinates to something like "x".

--EDIT--

The output I would want to get is:

[['x'], ['-'], ['-'], ['-'], ['-']]
[['-'], ['x'], ['-'], ['-'], ['-']]
[['-'], ['-'], ['x'], ['-'], ['-']]
[['-'], ['x'], ['-'], ['x'], ['-']]
[['-'], ['-'], ['x'], ['-'], ['x']]
[['-'], ['-'], ['-'], ['x'], ['-']]

and the code I have tried so far is:

for i in range(len(coordinates)):
    x = coordinates[i][0]
    y = coordinates[i][1]
    coordinate_system[y][x] = ["x"]

but all the items in the list changes to "x" with this code (like this)

[['x'], ['x'], ['x'], ['x'], ['x']]
[['x'], ['x'], ['x'], ['x'], ['x']]
[['x'], ['x'], ['x'], ['x'], ['x']]
[['x'], ['x'], ['x'], ['x'], ['x']]
[['x'], ['x'], ['x'], ['x'], ['x']]
[['x'], ['x'], ['x'], ['x'], ['x']]

Solution

  • There are some syntax errors in how you specified the list literal, and also how you are indexing into it - this gives you the output you need:

    coordinate_system = [
       [['-'], ['-'], ['-'], ['-'], ['-']],
       [['-'], ['-'], ['-'], ['-'], ['-']],
       [['-'], ['-'], ['-'], ['-'], ['-']],
       [['-'], ['-'], ['-'], ['-'], ['-']],
       [['-'], ['-'], ['-'], ['-'], ['-']],
       [['-'], ['-'], ['-'], ['-'], ['-']]]
    
    coordinates = [[0, 0], [1, 1], [2, 2], [3, 3], [4, 4], [1, 3], [2, 4], [3,5]]
    
    for coordinate in coordinates:
       coordinate_system[coordinate[1]][coordinate[0]] = ['x']
    
    coordinate_system
    

    Output:

     [[['x'], ['-'], ['-'], ['-'], ['-']],
     [['-'], ['x'], ['-'], ['-'], ['-']],
     [['-'], ['-'], ['x'], ['-'], ['-']],
     [['-'], ['x'], ['-'], ['x'], ['-']],
     [['-'], ['-'], ['x'], ['-'], ['x']],
     [['-'], ['-'], ['-'], ['x'], ['-']]]