-1

I've got a list of coordinate and i'm trying to change the value of these coordinate for something else in an NxN matrix as follows:

import numpy as np

point2 = [(1,3), (3,5), (6,7), (10,10)]

usine_ = ["" * i for i in range(10)]

usine = []
[usine.append(usine_) for i in range(10)]

for i in point2:
    x = i[0]
    y = i[1]

    del usine[y-1][x-1]
    usine[y-1].insert(x-1, "x")



usine = np.array(usine)

print(usine)

But my code seems to change the x value of the coordinate for every list in my list

[['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' '' '' 'x' '' '' '' 'x']
 ['x' '' 'x' '' '' 'x' '' '' '' 'x']
 ['x' '' 'x' '' '' 'x' '' '' '' 'x']]

I've been trying to figure out what I'm doing wrong but I can't put my finger on it.

bad_coder
  • 11,289
  • 20
  • 44
  • 72
  • What's the point of `"" * i`? – Manuel Apr 17 '21 at 14:23
  • 2
    Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – Manuel Apr 17 '21 at 14:24

3 Answers3

1

Just make few change in you logic, check this out:

import numpy as np

point2 = [(1,3), (3,5), (6,7), (10,10)]
usine = [[""]*10]*10
usine = np.array(usine)

for i in point2:
    x = i[0]
    y = i[1]
    usine[y-1][x-1] = 'x'

print(usine)

If you want to exploit more Numpy so check out this:

import numpy as np

point2 = [(1,3), (3,5), (6,7), (10,10)]
flat_point = [(i[1]-1)*10+(i[0]-1) for i in point2]
usine = [[""]*10]*10
usine = np.array(usine)

np.put(usine, flat_point, '*')
print(usine)
Davinder Singh
  • 2,060
  • 2
  • 7
  • 22
1

use this instead [usine.append(usine_.copy()) for i in range(10)]

Your code does not work because you append the same reference of usine_ to that usine. In my code, I create new references of usine_ before appending it to usine.

ACitronella
  • 43
  • 1
  • 4
0

usine is a list of lists. You add usine_ it it 10 times so usine contains 10 references to usine_ try:

import numpy as np

point2 = [(1,3), (3,5), (6,7), (10,10)]

usine_ = ["" * i for i in range(10)]

usine = []
[usine.append(usine_.copy()) for i in range(10)]

for i in point2:
    x = i[0]
    y = i[1]

    del usine[y-1][x-1]
    usine[y-1].insert(x-1, "x")



usine = np.array(usine)

print(usine)

That will add 10 copies os usine_

some other optional things to consider:

you don't need or use the list comprehension when you add the usine_ copies you can just use for i in range(10): usine.append(usine_) or get rid of the usine=[] line and replace it with usine = [usine_.copy() for i in range(10)] that's likely the most efficient way.

David Oldford
  • 1,127
  • 4
  • 11