Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing one number with another in PYTHON

I have declared a board array which is 10*10.I am reading the elements of the board which are 0, 1, and 2. After reading my board looks somewhat like this (shorter version 4*4)

   0  1  0  2 
   2  1  0  1 
   0  2  1  0 
   1  2  1  0 

Code:

board = [] 
for i in xrange(0, 10) 
    board.append(raw_input()) 

now i want to change all occurences of 0 to 1. I am not able to change it..what should i do..please write the modified code..(getting error as immutable)

Thanks for the answer it got changed.I should first covert the list to string then use replace function

like image 971
Ananth Upadhya Avatar asked Jul 06 '26 17:07

Ananth Upadhya


2 Answers

As I understood, you have a list and just want to replace all 0's with 1's right? If it's like that, you can try to convert that list to string and use the replace method. Like: board = str(board) and then board = board.replace('0','1'). And then convert back to list with eval built-in function. But this may be too slow for big lists .

UPDATE >> If you do not want to use strings you can also code this: If it is a 2d list like: L = [[1, 1, 0], [0, 2, 1], [0, 0, 0]] then:

for x in L:
    for y in x:
        if y == 0:
            x[x.index(y)] = 1

And if it is just a common list like L = [1, 0, 2, 1, 0, 1] then:

for x in L:
    if x == 0:
        L[L.index(x)] = 1
like image 61
Shalva123 Avatar answered Jul 09 '26 05:07

Shalva123


for i in xrange(10):
    for j in xrange(10):
        if board[i][j] == 0:
            board[i][j] = 1

This should works. If not, please show me how you create your board table.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!