如何检查一组必需元素的所有子列表

How to check all sublists for a set of required elements

一个列表将包含 9 个子列表,每个子列表包含 9 个数字。 每个子列表必须包含任何顺序的数字 1-9(即不能有 repetition/missing 个数字。) 如何检查是否满足此条件?

valid_list 将 return 为真,在 valid_list 中将 return 为假。

valid_list = 
       [[1,3,5,7,9,8,6,4,2],[1,2,3,4,5,6,7,8,9],[5,4,3,2,1,9,8,7,6],
        [1,3,5,7,9,8,6,4,2],[1,2,3,4,5,6,7,8,9],[5,4,3,2,1,9,8,7,6],
        [1,3,5,7,9,8,6,4,2],[1,2,3,4,5,6,7,8,9],[5,4,3,2,1,9,8,7,6]]

invalid_list =
   [[1,1,1,1,1,1,1,1,1],[2,1,2,1,2,1,2,1,2],[9,8,7,7,7,7,6,5,6],
    [1,1,1,1,1,1,1,1,1],[2,1,2,1,2,1,2,1,2],[9,8,7,7,7,7,6,5,6],
    [1,1,1,1,1,1,1,1,1],[2,1,2,1,2,1,2,1,2],[9,8,7,7,7,7,6,5,6]]

我确信 all() 可以做到这一点,但我不知道怎么做。我试过很多东西,比如..

lists = [[1, 2, 3, 4, 5, 7, 6, 8, 9], [1, 2, 3, 4, 5, 7, 6, 8, 9]]
all(x in [[1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9]] for x in list in lists)
>>>(Would return true if not erroneous)
lists = [[1, 2, 3, 4, 5, 7, 6, 8, 9], [1, 2, 3, 4, 5, 7, 6, 8, 9]]
all([[1,2,3,4,5,6,7,8,9] == sorted(el) for el in lists])

作为扩展,虽然您没有要求,但您可以选择接受重复但拒绝遗漏的数字,方法是将 lists 中的每个 list 转换为 set 和回到 list.

all([[1,2,3,4,5,6,7,8,9] == sorted(list(set(el))) for el in lists])

我们可以使用sort函数并将结果与​​包含1到9的列表进行比较

  def check_duplicated(lst):
        for l in lst:
            if sorted(l) != list(range(1, 10)):
                return False
        return True

我会先定义一个验证器函数来验证子列表。然后使用 all().

调用这个验证器

例如

def isValidList(myList):
    return True if len(set(myList)) == 9 and max(myList) == 9 and min(myList) == 1 else False

## returns True if all sublists are valid
all(isValidList(subList) for subList in some_list)

您可以通过转换为 set 从内部列表中删除重复项,然后检查该集合是否与有效的数字集合相匹配

valid_list = [
    [1, 3, 5, 7, 9, 8, 6, 4, 2],
    [1, 2, 3, 4, 5, 6, 7, 8, 9],
    [5, 4, 3, 2, 1, 9, 8, 7, 6],
    [1, 3, 5, 7, 9, 8, 6, 4, 2],
    [1, 2, 3, 4, 5, 6, 7, 8, 9],
    [5, 4, 3, 2, 1, 9, 8, 7, 6],
    [1, 3, 5, 7, 9, 8, 6, 4, 2],
    [1, 2, 3, 4, 5, 6, 7, 8, 9],
    [5, 4, 3, 2, 1, 9, 8, 7, 6],
]


invalid_list = [
    [1, 1, 1, 1, 1, 1, 1, 1, 1],
    [2, 1, 2, 1, 2, 1, 2, 1, 2],
    [9, 8, 7, 7, 7, 7, 6, 5, 6],
    [1, 1, 1, 1, 1, 1, 1, 1, 1],
    [2, 1, 2, 1, 2, 1, 2, 1, 2],
    [9, 8, 7, 7, 7, 7, 6, 5, 6],
    [1, 1, 1, 1, 1, 1, 1, 1, 1],
    [2, 1, 2, 1, 2, 1, 2, 1, 2],
    [9, 8, 7, 7, 7, 7, 6, 5, 6],
]


def validate_lists(lists):
    valid_set = set(range(1, 10))
    return all(set(list_) == valid_set for list_ in lists)

print(validate_lists(valid_list) == True)
print(validate_lists(invalid_list) == False)