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
Luan Pacheco is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
Here is a set
comprehension to achieve what you want:
my_list = [
[0, 0, 1],
[1, 0, 0],
[0, 1, 0]
]
coordinates = set(
(row, column)
for row in range(len(my_list))
for column in range(len(my_list[row]))
if my_list[row][column] == 1
)
print(coordinates)
This should print:
{(1, 0), (0, 2), (2, 1)}