【问题标题】:How do a check if a column or row in a nested list has the same string如何检查嵌套列表中的列或行是否具有相同的字符串
【发布时间】:2021-07-21 14:03:32
【问题描述】:

我需要检查一个嵌套列表是否有一列具有相同的字符串

grid = [
  ["x", " ", "x"],
  ["x", " ", " "],
  ["x", "x", "x"]
]
#if grid has a column or row with the same string (such as the first column and last row) then it will say "yes"

我只对行做到了:

grid = [
  ["x", " ", "x"],
  ["x", " ", " "],
  ["x", " ", "x"]
]
print(grid)


row = ['x', 'x', 'x']


if row in grid:
  print("Yes")
else:
  print("no")

【问题讨论】:

  • 我建议发布一个示例以及您迄今为止尝试过的内容
  • 刚刚编辑了帖子以显示我到目前为止所做的事情(它只适用于行)
  • 这能回答你的问题吗? python tic tac toe winning conditons

标签: python python-3.x list nested-lists


【解决方案1】:

一个简单的方法来做你需要的就是转置你的主网格来检查列,如下所示:

gridTranspose = list(zip(*grid))

这将基本上反转网格中的行和列。

接下来,将您的列保存为一行(例如)

如果您的网格是:

[ 1 1 0 ]

只需以相同的方式制作变量(列 = [1, 1, 0])

那么它应该可以工作了!

【讨论】:

  • 不会说谎,我还是有点困惑。我知道这是做什么的(因为你已经解释过了),但我不知道如何在我的代码中实现它
  • 给我一些时间,我会尽力给你一个例子
【解决方案2】:

-1 表示不一样

grid = [
  ["x", " ", "x"],
  ["x", " ", " "],
  ["x", "x", "x"]
]

row_same = [index if all(map(lambda x: x==i[0], i)) else -1 for index, i in enumerate(grid)] 
#[-1, -1, 2]
column_same = [j if all(map(lambda x: x==grid[0][j], [i[j] for i in grid])) else -1 for j in range(len(grid[0]))] 
#[0, -1, -1]

【讨论】:

    【解决方案3】:

    我有一个简单易懂的解决方案。

    因此,基本思想是获取行列表并创建一个新的列列表,然后在它们之间进行检查 -

    num = range(len(grid)) # Just an extra var, so that it is readable
    
    lst_of_columns = [[grid[j][i] for j in num] for i in num]
    # This makes a list of columns. Take it slow, print it and understand the logic
    
    for i in num: # These lines check if rows and columns are same
        for j in num:
            if grid[i] == lst_of_columns[j]: # grid[i] = row 1,2,3...
                print('yes')                 # lst_of_columns[j] = columns 1,2,3
    
            else:
                print('no')
    

    我希望你理解这背后的逻辑。 此外,这适用于任意数量的行和列

    【讨论】:

      猜你喜欢
      • 2021-12-30
      • 2015-01-22
      • 2019-04-20
      • 2017-04-15
      • 2013-08-21
      • 2021-12-17
      • 1970-01-01
      • 1970-01-01
      • 2021-11-12
      相关资源
      最近更新 更多