【问题标题】:How to first iterate columns and then rows如何先迭代列然后再迭代行
【发布时间】:2017-03-18 22:16:20
【问题描述】:

我正在编写一个井字游戏,我被困在代码应该检查玩家是否垂直获胜的步骤中,我知道 c++ 的朋友告诉我首先迭代通过 COLUMNS 然后 ROWS 进行过程更轻松。不知道它在 python 中是如何工作的。

例如,玩家进入 4x4 桌,一段时间后这是他的结果。

[0,1,0,0]
[0,1,0,0]
[0,1,0,0]
[0,1,0,0]

他说,如果我先遍历列然后遍历行,那么它会是这样的:

CHECK,1,0,0
CHECK,1,0,0
CHECK,1,0,0
CHECK,1,0,0

然后列索引变为 1

0,CHECK,0,0
0,CHECK,0,0
0,CHECK,0,0
0,CHECK,0,0

抱歉解释不好...

【问题讨论】:

  • 你试过写简单的嵌套for循环吗?
  • 我尝试了row > column,但我的朋友说我应该循环遍历该行内的列,然后再循环该行本身。
  • 可能是您正在寻找的。 stackoverflow.com/questions/903853/…

标签: python multidimensional-array


【解决方案1】:

您可以使用内置的all()函数来检查所有元素是否为True,
zip(*table) 符号为Row-to-Column Transposition

mytable1 = [[0,0,0,0],[1,1,1,1],[0,0,0,0],[0,0,0,0]]
mytable2 = [[0,0,1,0],[0,0,1,0],[0,0,1,0],[0,0,1,0]]
mytable3 = [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]
mytable4 = [[0,0,0,1],[0,0,1,0],[0,1,0,0],[1,0,0,0]]
mytable5 = [[0,1,0,0],[0,0,1,0],[0,1,0,0],[1,0,0,0]]
mytable6 = [[2,1,0,0],[2,0,1,0],[2,1,0,0],[2,0,1,0]]
mytable7 = [[2,1,0,0],[0,2,1,0],[0,1,2,0],[0,0,1,2]]

def hasWon(table,player_no):
    #check rows
    for row in table: 
        if all([e==player_no for e in row]):
            return True
    #check columns
    for column in zip(*table): 
        if all([e==player_no for e in column]):
            return True
    #check diagonals
    if all([table[i][i]==player_no for i in range(len(table)) ]): 
        return True
    if all([table[-i-1][i]==player_no for i in range(len(table))]):
        return True
    return False



print(hasWon(mytable1,1))
print(hasWon(mytable2,1))
print(hasWon(mytable3,1))
print(hasWon(mytable4,1))
print(hasWon(mytable5,1))
print(hasWon(mytable6,2))
print(hasWon(mytable7,2))

输出:

True
True
True
True
False
True
True

【讨论】:

  • 但是如果其他玩家是'2'而不是1。那我该怎么办呢?
【解决方案2】:

这样的?

In [22]: import numpy as np

In [23]: a=np.array(range(15)).reshape(3,5)

In [24]: a
Out[24]: 
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])

In [25]: [ [x[i] for x in a] for i in range(a.shape[1])]
Out[25]: [[0, 5, 10], [1, 6, 11], [2, 7, 12], [3, 8, 13], [4, 9, 14]]

【讨论】:

  • 如果我有for row in table: 和里面有for column in row -- 我如何更改订单?
  • 我的x in a 对应于您的row in table。列将通过每行的索引访问,因此您需要列数 (shape[1]) 并对其进行迭代。
猜你喜欢
  • 2023-03-17
  • 1970-01-01
  • 2022-02-11
  • 1970-01-01
  • 1970-01-01
  • 2013-09-15
  • 1970-01-01
  • 2013-07-01
  • 2016-02-25
相关资源
最近更新 更多