Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 查找嵌套列表中元素的所有索引_Python 3.x_List_Indexing_Nested Loops_Tic Tac Toe - Fatal编程技术网

Python 3.x 查找嵌套列表中元素的所有索引

Python 3.x 查找嵌套列表中元素的所有索引,python-3.x,list,indexing,nested-loops,tic-tac-toe,Python 3.x,List,Indexing,Nested Loops,Tic Tac Toe,Tic tac toe,其中电路板表示为[['x',x',x'],['','','', ['','',''] 我们想确认船上所有的空方块。电路板上的空正方形位置将作为(行、列)元组返回 完成函数empty_squares(board),它返回元组列表,其中每个元组是空正方形的(行、列) 这就是我到目前为止得到的,它返回所有正方形的元组,但我只想要空的 def empty_squares(board): check = ' ' target_cell_list = [] f

Tic tac toe,其中电路板表示为[['x',x',x'],['','','', ['','','']

我们想确认船上所有的空方块。电路板上的空正方形位置将作为(行、列)元组返回

完成函数empty_squares(board),它返回元组列表,其中每个元组是空正方形的(行、列)

这就是我到目前为止得到的,它返回所有正方形的元组,但我只想要空的

def empty_squares(board):
    check = ' '
    target_cell_list = []
    for i in range(len(board)):
        for j in range(len(board[i])):
            target_cell_list.append((i, j))
    return target_cell_list
添加if语句
您可以稍微改变您的方法,使其更“pythonic”。避免嵌套for循环,您可以将列表理解与内置的
enumerate
语句一起使用。因此,
空面积
可以如下所示:

def empty_sqares(board):
    return [(row_idx, col_idx) for row_idx, row in enumerate(board)
            for col_idx, item in enumerate(row) if item == ' ']
要想弄清楚的最重要的事情是
enumerate
做什么。简言之,它遍历
iterable
(例如list、list、list、list of objects等),并为每个元素返回一个元组,其中包含一个计数(从开始默认为0)和通过迭代iterable获得的值。资料来源:

那么代码中发生了什么:

  • 对于行_idx,枚举(线路板)中的行
    遍历
    线路板中的行
    。因为
    board
    (行)的项目是列表,所以
    enumerate(board)
    的连续结果是行索引(
    row\u idx
    )和行内容(
    row
    ,它是字符串列表)。例如,
    enumerate(board)
    的第一个“迭代”结果将是:
    row\u idx=0
    row=['x','x','x']
  • 对于列idx,枚举(行)中的项
    遍历
    ,选择
    中的每个元素,并将其分配给
    。例如,
    enumerate(row)
    的第一个“迭代”结果将是:
    col\u idx=0
    item='x'
  • 如果item=''
    执行检查所选字符(在您的情况下,您有两个选项
    'x'
    '或
    '
    )是否等于单个空格
  • 。。。如果check为true,则形成tuple
    (row\u idx,col\u idx)
  • 整件事都用方括号括起来,形成元组列表。但请记住,只有当满足上述条件时,新元组才会附加到结果中

您可以尝试使用
if
语句来包装您的
.append
。您尝试过什么来只查找空字段?
def empty_sqares(board):
    return [(row_idx, col_idx) for row_idx, row in enumerate(board)
            for col_idx, item in enumerate(row) if item == ' ']