-1

For example I have the following list of lists:

 matrix = [['.', 'W', '.'], 
           ['.', 'W', '.'],
           ['W', '.', '.']]

I want to have a list with all rows, column indexes.

In this answer they show how to do it for a single list.

However I want to do it for nested list. There are more then one examples of this like this and this

So this works for me:

l = [[(i,j) for j,el in enumerate(row) if el == 'W'] for i,row in enumerate(matrix)]
flat_list = [item for sublist in l for item in sublist]

>> [(0, 1), (1, 1), (2, 0)]

However how would I do this with one list comprehension statement?

2
  • It seems that your code currently works, and you are looking to improve it. Generally these questions are too opinionated for this site, but you might find better luck at CodeReview.SE. Remember to read their requirements as they are a bit more strict than this site. Commented Nov 12, 2019 at 14:20
  • @PaulRoub maybe I asked the question wrong. I was looking for the answer from zipa. I didn't understand the syntax of list comprehension enough. Commented Nov 12, 2019 at 15:07

1 Answer 1

1

Other than doing it in one line:

[(i, j) for i, row in enumerate(matrix) for j, el in enumerate(row) if el == 'W']
#[(0, 1), (1, 1), (2, 0)]

You can also use numpy:

import numpy as np
list(zip(*np.where(np.array(matrix)=='W')))
#[(0, 1), (1, 1), (2, 0)]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I didn't understand the syntax of list comprehension enough. I ran it with %%timeit and the list comprehension was 1.36 µs ± 7.2 ns per loop vs 4.55 µs ± 12.9 ns per loop with numpy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.