简体   繁体   English

检查每个数字python

[英]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? 我收到此错误TypeError:无法散列的类型:'list'我是否必须将列表转换为其他内容?

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(). 列表不能是集合的元素,因此您不能将列表的列表传递给set()。 You need to unravel the list of lists to a single list, then pass to set (so integers are your set elements). 您需要将列表列表分解为单个列表,然后传递给set(因此整数是set元素)。

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

Your matrix is a list of lists. 您的matrix是一个列表列表。 When you write set(matrix) , Python tries to create a set of all rows of the matrix. 当您编写set(matrix) ,Python会尝试创建一组矩阵的所有行。 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. “ set”在列表列表上不起作用,但在元组列表上很好用。 So use the below code : 因此,使用以下代码:

matrixList.append(tuple(row))

instead of : 代替 :

matrixList.append(row)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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