I have the following list:
list = [[0, 0, 1],
[1, 0, 0],
[0, 1, 0]]
My goal is to return from this list, a set of tuples that contain the coordinates (row, column) of each value equal to 1
.
The correct answer to the above code is:
{(0, 2), (1, 0), (2, 1)}
I'm working on my list comprehension knowledge. I manage to do this with a for
loop and an index, but i want cleaner code. If the solution can be using list comprehension I would appreciate it
you can try this function in which you can pass the value and it will give you all the coordinates. I use list comprehaninsion.
def find_coordinates(my_list, value):
return {(row, col) for row, sub_list in enumerate(my_list) for col, val in enumerate(sub_list) if val == value}
# Example usage:
my_list = [[0, 0, 1],
[1, 0, 0],
[0, 1, 0]]
value = 1
coordinates = find_coordinates(my_list, value)
The Output is:
{(1, 0), (0, 2), (2, 1)}