当且仅当所有给定条件都为真

时间:2014-11-19 09:05:49

标签: python logical-operators

import numpy as np    
def data_verify(source):
        rows = [x.strip().split(' ') for x in open(source)]
        columns = zip(*rows)
        blocks = np.array(rows).reshape((3,3,3,3)).transpose((0,2,1,3)).reshape((9,9))
            #check iff, see further
                return rows, columns, blocks
            else:
                return False

在txt中有一个数独网格:

3 2 7 4 8 1 6 5 9
1 8 9 3 6 5 7 2 4
6 5 4 2 7 9 8 1 3
7 9 8 1 3 2 5 4 6
5 6 3 9 4 7 2 8 1
2 4 1 6 5 8 3 9 7
8 1 2 7 9 3 4 6 5
4 7 5 8 1 6 9 3 2
9 3 6 5 2 4 1 7 8

该函数收集所有相关数据,如果行的长度与列相同,则返回相应的行,列和块。 (还有一些其他功能可以确定这个谜题是否合法)。我认为将第一行与所有列进行比较就足够了(反之亦然,并没有产生影响)。如何创建类似以下内容的检查:

for i in range(len(rows)):
    if len(row[0]) == len(column[i]):
        #do something only if all of the lengths check out

2 个答案:

答案 0 :(得分:3)

使用all

if all(len(row[0]) == len(column[i]) for i in range(len(rows))):
    #do something only if all of the lengths check out

答案 1 :(得分:0)

您可以在for循环中运行检查并在有任何不匹配时设置标志,此示例将检查所有列的所有行:

match = True
for r in row:
    for c in column:
        if len(c) != len(r):
            match = False

# Only continue if match == True