numpy - How to 'unpack' a list or tuple in Python -
i'm writing python program play tic tac toe, using numpy arrays "x" represented 1
, "o" 0
. class includes function place mark on board:
import numpy np class board(): def __init__(self, grid = np.ones((3,3))*np.nan): self.grid = grid def place_mark(self, pos, mark): self.grid[pos[0],pos[1]] = mark
so that, example,
board = board() board.place_mark([0,1], 1) print board.grid
yields
[[ nan 1. nan] [ nan nan nan] [ nan nan nan]]
i wondering if pos[0], pos[1]
argument in place_mark
function somehow replaced 'unpacked' contents of pos
(which list of length 2). in ruby done using splat operator: *pos
, not appear valid syntax in python.
with numpy, there's difference between indexing lists , multi-dimensional indexing. self.grid[[0,1]]
equivalent concatenating self.grid[0]
, self.grid[1]
, each 3x1 arrays, 3x2 array.
if use tuples instead of lists indexing, correctly interpreted multi-dimensional indexing: self.grid[(0, 1)]
interpreted same self.grid[0, 1]
.
there *
operator unpacking sequences, in context of function arguments only, @ least in python 2. so, lists this:
def place_mark(self, mark, x, y): self.grid[x, y] = mark place_mark(1, *[0, 1])
Comments
Post a Comment