简体   繁体   English

如何在Python中“解压”列表或元组

[英]How to 'unpack' a list or tuple in Python

I'm writing a Python program to play Tic Tac Toe, using Numpy arrays with "X" represented by 1 and "O" by 0 . 我正在编写一个Python程序,使用Numpy数组播放“井字游戏”,其中“ X”由1表示,“ O”由0 The class includes a function to place a mark on the board: 该类包括在板上放置标记的功能:

import numpy as 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, for example, 这样,例如

board = Board()
board.place_mark([0,1], 1)
print board.grid

yields 产量

[[ nan   1.  nan]
 [ nan  nan  nan]
 [ nan  nan  nan]]

I was wondering if the pos[0], pos[1] argument in the place_mark function could somehow be replaced by the 'unpacked' contents of pos (which is always a list of length 2). 我想知道place_mark函数中的pos[0], pos[1]参数place_mark能以某种方式由pos的“未place_mark ”内容(始终是长度为2的列表)替换。 In Ruby this would be done using the splat operator: *pos , but this does not appear to be valid syntax in Python. 在Ruby中,可以使用splat运算符*pos来完成,但这在Python中似乎不是有效的语法。

With Numpy, there's a difference between indexing with lists and multi-dimensional indexing. 使用Numpy,列表索引和多维索引之间是有区别的。 self.grid[[0,1]] is equivalent to concatenating self.grid[0] and self.grid[1] , each 3x1 arrays, into a 3x2 array. self.grid[[0,1]]等效于将self.grid[0]self.grid[1] (每个3x1数组)串联为3x2数组。

If you use tuples instead of lists for indexing, then it will be correctly interpreted as multi-dimensional indexing: self.grid[(0, 1)] is interpreted the same as self.grid[0, 1] . 如果使用元组而不是列表进行索引,则它将被正确解释为多维索引: self.grid[(0, 1)]self.grid[0, 1]

There is a * operator for unpacking sequences, but in the context of function arguments only, at least in Python 2. So, with lists you could also do this: 有一个*运算符可用于解包序列,但仅在函数参数的上下文中,至少在Python 2中如此。因此,使用列表也可以执行以下操作:

def place_mark(self, mark, x, y):
    self.grid[x, y] = mark

place_mark(1, *[0, 1])

NB. NB。 (Expanded usefulness of * in Python 3) (在Python 3中扩展了*用途)

As suggested by Lukasz, the input argument should be a tuple. 正如Lukasz所建议的那样,输入参数应该是一个元组。 In this example it can be converted to one: 在此示例中,可以将其转换为一个:

def place_mark(self, pos, mark):
    self.grid[tuple(pos)] = mark

My question is not the same What is the pythonic way to unpack tuples? 我的问题不一样。解开元组的pythonic方法是什么? because pos does not constitute the input arguments to a function, but rather the indices of a 2-dimensional array. 因为pos并不构成函数的输入参数,而是构成二维数组的索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM