Lucy L - 3 months ago 9
Python Question

# Search for a part of a tuple in a list of tuples

I am working on a sudoku solver in python. The coordinates of the boxes are given by this code:

``````for row in range(1, 10):
for column in range(1,10):
boxes.append((row, column))
``````

Later, I have a list of tuples in the format of (row, column, box, number). I need to organize them so that they are in the order of the first list. Both are the same length, so I though I could make a new list by finding each (row, column) pair in the larger list. In other words, for the item (1, 1), I want to find a tuple in the other list where item 0 is '1' and item 1 is '1'.

How can I do this?

I believe this should work for finding the (row, column) pair:

``````entry = [e for e in tuple_list if (e[0] == row and e[1] == column)][0]
``````

You essentially end up with a list of all entries `e` that match the (1, 1) pattern and then get the first of these using `[0]`.

Use this in a loop to find each one individually:

``````sorted_tuple_list = []
for row in range(1, 10):
for column in range(1,10):
entry = [e for e in tuple_list if (e[0] == row and e[1] == column)][0]
sorted_tuple_list.append(entry)
``````