简体   繁体   中英

Checking whether list in a dictionary is the same as another list?

I'm trying to make a Sudoku solver, and at the moment I'm making the part which checks if it has been solved, but I've got abit stuck. The grid is made of a list of 81 numbers (9*9), and then I have dictionaries which group them into rows, columns and boxes, eg:

self.rows = {'toptop':self.board[0:9],'topmid':self.board[9:18],'topbottom':self.board[18:27],  
'midtop':self.board[27:36],'midmid':self.board[36:45],'midbottom':self.board[45:54]

, The bit that I'm stuck with is checking whether each row, or column or box have numbers 1-9 in them. I've experimented abit and tried

self.winning = [1,2,3,4,5,6,7,8,9]
[x for x in self.rows.values() if (x == y for y in self.winning)]

But that just returned every value grouped into rows. I also tried variations to this, and some would return the lists which had numbers 1-9 in, but they often had duplicates; they would never show the lists with 1-9 exclusively. How could I achieve this? Thanks

It is hard to tell from what little code you have posted exactly where your problem lies, or what to change in order to make it work, but based on your question title and the information that you provided (that you are solving Sudoku) I can say that the following will help you.

In order to compare that items in a list are or aren't in another list, we have to determine the scope.

Let us say we have two lists, A and B.

A == B
# lists are in the same order with the same items.
all(a in B for a in A)
# all items in A are in B. (order not checked)
all(b in A for b in B)
# all items in B are in A. (order not checked)
all(A[i] == B[i] for i in range(len(A)))
# all items in A are in B. (order checked) (len(A) <= len(B))
all(B[i] == A[i] for i in range(len(B)))
# all items in B are in A. (order checked) (len(B) <= len(A))

This is a generator you can use on lists of equal length to check on what indices they are True/False

def gen_diff(A, B):
    if len(A) != len(B):
        raise IndexError('lists not of same length')
    for i in range(len(A)):
        if A[i] == B[i]:
            yield (True, i)
        else:
            yield (False, i)

我认为您不能将列表与==进行比较,但是这样的方法应该可以工作:

len(x)==len(y) and all(x[i] == y[i] for i in range(len(x)-1))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM