Skip to content Skip to sidebar Skip to footer

Python: Replacing Item In A List Of Lists

Heres my code: data = [ [5,3,0,0,7,0,0,0,0], [6,0,0,1,9,5,0,0,0], [0,9,8,0,0,0,0,6,0], [8,0,0,0,6,0,0,0,3], [4,0,0,8,0,3,0,0,1], [7,0,0,0,2,0,0,0,6], [0,6,0,0,0,0,2,8,0], [0,0,0,4,

Solution 1:

You need to break for look as soon as you find the necessary element:

item = [1,2,3,4,5,6,7,8,9]
for element in item:
    if element not in z:
            print element
            breakdata[x][y] = element 
print data[x][y]

Solution 2:

Works just fine for me...

>>>data = [...[5,3,0,0,7,0,0,0,0],...[6,0,0,1,9,5,0,0,0],...[0,9,8,0,0,0,0,6,0],...[8,0,0,0,6,0,0,0,3],...[4,0,0,8,0,3,0,0,1],...[7,0,0,0,2,0,0,0,6],...[0,6,0,0,0,0,2,8,0],...[0,0,0,4,1,9,0,0,5],...[0,0,0,0,8,0,0,7,9]...]>>>element = 4>>>x = 0>>>y = 0>>>print data[0][0]
5
>>>data[x][y] = element>>>print data[0][0]
4
>>>

Solution 3:

You seem to have tabbed out your last line, which gives me an error in the Python interpreter. If I remove that tab, it works.

Your array data has changed. Maybe you aren't printing it out so you don't know that it changed?

Solution 4:

What version of python are you running? Can you try it from the command line and post the results, like below? It seems to be working for me. I basically copied and pasted straight from your post.

Python 2.6.4 (r264:75706, Dec  7 2009, 18:45:15) 
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>data = [...[5,3,0,0,7,0,0,0,0],...[6,0,0,1,9,5,0,0,0],...[0,9,8,0,0,0,0,6,0],...[8,0,0,0,6,0,0,0,3],...[4,0,0,8,0,3,0,0,1],...[7,0,0,0,2,0,0,0,6],...[0,6,0,0,0,0,2,8,0],...[0,0,0,4,1,9,0,0,5],...[0,0,0,0,8,0,0,7,9]...]>>>>>>element = 4>>>x = 0>>>y = 0>>>>>>data
[[5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 6, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5], [0, 0, 0, 0, 8, 0, 0, 7, 9]]
>>>data[x][y] = element>>>data
[[4, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 6, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5], [0, 0, 0, 0, 8, 0, 0, 7, 9]]
>>>

Solution 5:

The only thing wrong I see in your code is that the very last line is at a different indentation level. Putting it at the same level of the rest of the code works fine. :)

You may also be interested in the pprint module:

>>> from pprint import pprint
>>> pprint(data)
[[4, 3, 0, 0, 7, 0, 0, 0, 0],
 [6, 0, 0, 1, 9, 5, 0, 0, 0],
 [0, 9, 8, 0, 0, 0, 0, 6, 0],
 [8, 0, 0, 0, 6, 0, 0, 0, 3],
 [4, 0, 0, 8, 0, 3, 0, 0, 1],
 [7, 0, 0, 0, 2, 0, 0, 0, 6],
 [0, 6, 0, 0, 0, 0, 2, 8, 0],
 [0, 0, 0, 4, 1, 9, 0, 0, 5],
 [0, 0, 0, 0, 8, 0, 0, 7, 9]]

A little easier to read!

Post a Comment for "Python: Replacing Item In A List Of Lists"