Lucy L - 10 months ago 76

Python Question

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?

Answer

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)
```

Source (Stackoverflow)