0

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]

3
  • 1
    What if there's more than one 0 in the sublist? Commented Mar 28, 2012 at 19:43
  • 5
    if board were a NumPy array, you could use zip(*numpy.where(a == 0)). Commented Mar 28, 2012 at 19:43
  • 1
    @IgnacioVazquez-Abrams Does this matter here? I'm not sure, but I think he's always printing the whole boxes... so I think there could also be 3 zeros in, but it would still work. Commented Mar 28, 2012 at 19:45

2 Answers 2

4

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:

zeroes = [(x, box.index(0)) for x, box in enumerate(board) if 0 in box]
Sign up to request clarification or add additional context in comments.

3 Comments

I did not know about the enumerate function that will diffidently come in handy. Is there a way to condense the for if loop in to one line?
@GeneralZero: This can be written in one line as zeroes = [(x, box.index(0)) for x, box in enumerate(box) if 0 in box]. Note that this code (as well as the code in the above answer) will at most include one zero per row -- not sure if this is what you want.
@SvenMarnach Thank you for pointing that out. I in fact do need more than one per row
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.