Python: Accessing Values For Dict Key Made Using Variables
Hi I've been coding a console version of Minesweeper just to learn some of the basics of Python. It uses a coordinate system that is recorded in a dictionary. Now, I have been a开发者_运维知识库ble to implement it successfully but accessing or assigning a value to a specific coordinate key using variables for the "x,y" of the coordinate seems... clunky. There are two different ways that I've come up with but they don't seem very elegant when I have to use them so often.
for i in range(1, ROWS+1):
for j in range(1, COLS+1):
mine_field["%i,%i" % (i,j)] = 0
or
for i in range(1, ROWS+1):
for j in range(1, COLS+1):
mine_field[",".join([i, j])] = 0
It works well enough but it does start to look messy when assigning or swapping values. Is there a better way that this can be done?
Thanks in advance.
Why not simply use a tuple as the key?
for i in range(1, ROWS+1):
for j in range(1, COLS+1):
mine_field[(i, j)] = 0 # you don't even need the parentheses!
Using this method, you can use comma-separated indices like so:
d = {(1,2):3}
print d[1, 2] # will print 3
And BTW why are you using one-based indices?
If you make mine_field a list of lists, then you can use nicer syntax:
mine_field = [[0]*ROWS for i in range(COLS)]
mine_field[i][j] = 1
精彩评论