简体   繁体   English

Python列表索引

[英]Python List Indexes

I have a dual list and I am wondering what it the best way to get the indexes of the zeros in the array 我有一个双重列表,我想知道什么是获取数组中零索引的最佳方法

board =[[1,2,0],
    [2,1,2],
    [1,1,0]]

for boxes in board:
    if 0 in boxes:
        print boxes

like this but instead I want to have return [0,2] [2,2] 这样,但我想返回[0,2] [2,2]

Your question is very vague (what about multiple zeroes in one of the inner lists), feel free to comment if you are looking for something else: 您的问题非常模糊(内部列表之一中的多个零是什么),如果您要查找其他内容,请随时发表评论:

zeroes = []
for x, box in enumerate(board):
    if 0 in box:
        zeroes.append((x, box.index(0)))
print zeroes

With your given lists, this prints 用您给定的列表,打印

[(0, 2), (2, 2)]

A shorter, more pythonic version would be using a list comprehension like this: 一个更短,更pythonic的版本将使用像这样的列表理解:

zeroes = [(x, box.index(0)) for x, box in enumerate(board) if 0 in box]

You could use a list comprehension: 您可以使用列表理解:

[(i, j) for i in range(3) for j in range(3) if board[i][j] == 0]

This will include multiple zeros per row if present. 如果存在的话,这将包括每行多个零。

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

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