简体   繁体   中英

Check each number python

I am trying to read a file and check to see that every number is present, all unique. I tried checking the equality of the length of the list and the length of the set. I get this error TypeError: unhashable type: 'list' Do i have to convert the list to something else?

Here is code

def readMatrix(filNam):
    matrixList = []
    numFile = open(filNam, "r")
    lines = numFile.readlines()
    for line in lines:
        line = line.split()
        row = []
        for i in line:
            row.append(int(i))
        matrixList.append(row)
    return matrixList

def eachNumPresent(matrix):
    if len(matrix) == len(set(matrix)):
        return True
    else:
        return False

A list cannot be an element of a set, so you cannot pass a list of lists to set(). You need to unravel the list of lists to a single list, then pass to set (so integers are your set elements).

unraveled = [x for line in matrix for x in line]
return len(unraveled) == len(set(unraveled))

Your matrix is a list of lists. When you write set(matrix) , Python tries to create a set of all rows of the matrix. Your rows are lists, which are mutable and unhashable.

What you want is a set of all values in the matrix. You can count it with an explicit loop:

all_values = set()
for row in matrix:
  all_values.update(row)
# here all_values contains all distinct values form matrix

You could also write a nested list comprehension :

all_values = set(x for row in matrix for x in row)

"set" doesn't work on list of lists but works fine on list of tuples. So use the below code :

matrixList.append(tuple(row))

instead of :

matrixList.append(row)

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