问题描述
我想遍历一个矩阵,如果遇到值为 1 的值,则将其添加到列表中,如果遇到值为 2 的值,则将其添加到另一个矩阵,然后最后比较 2 个列表并确定获胜者。 但是我收到一个错误并且不理解 any() 或 all() 方法。 也在寻找面向对象方面的一般改进,因为我无法将某些方法集成到我的类中。
for i in "This is a test":
action = ActionChains(driver)
action.key_down(i).pause(1).key_up(i).perform()
time.sleep(1)
解决方法
使用 numpy.all
测试 numpy 数组中的所有字段是否具有相同的值:
if num == 1:
if np.all(num == 1):
# [...]
使用 numpy.any
判断 numpy 数组中的任何数组元素是否具有特定值:
if np.any(num == 1):
# [...]
但是,如果要计算网格中的值,则必须使用 2 个嵌套循环。请注意,您必须在 head 之前清除列表:
self.player1_pieces.clear()
self.player2_pieces.clear()
for row in self.board_body:
for num in row:
if num == 1:
self.player1_pieces.append(1)
elif num == 2:
self.player2_pieces.append(2)
p1 = len(self.player1_pieces)
p2 = len(self.player2_pieces)
或者你可以flatten
多维数组:
self.player1_pieces = []
self.player2_pieces = []
for num in self.board_body.flatten():
if num == 1:
self.player1_pieces.append(1)
elif num == 2:
self.player2_pieces.append(2)
p1 = len(self.player1_pieces)
p2 = len(self.player2_pieces)
然而,您根本不需要 self.player1_pieces
和 self.player2_pieces
列表。使用 numpy.count_nonzero
:
p1 = np.count_nonzero(self.board_body == 1)
p2 = np.count_nonzero(self.board_body == 2)