【问题标题】:Isinstance function to check the elements given fits in my matrixIsinstance 函数检查给定的元素是否适合我的矩阵
【发布时间】:2020-11-14 16:11:21
【问题描述】:

我想创建一个函数来检查给定的标签是否适合。我的矩阵应该是一个 3x3 的 3 个元组,每个元组有 3 个整数。

我希望这种互动发生:

>>> tab = ((1,0,0),(-1,1,0),(1,-1,-1))
>>> tabuleiro(tab)
True
>>> tab = ((1,0,0),(’O’,1,0),(1,-1,-1))
>>> tabuleiro(tab)
False
>>> tab = ((1,0,0),(-1,1,0),(1,-1))
>>> tabuleiro(tab)
False

我现在只有:

def tabuleiro(tab):

    return isinstance(tab, tuple) and len(tab) == 3 and \
           all((isinstance( l, tuple) and len (l) == len(tab[0])) for l in tab) and len (tab[0]) == 3 and \ 
(....)

【问题讨论】:

    标签: python matrix isinstance


    【解决方案1】:

    如果您将其分解为组的一个函数和组中每个成员的另一个函数,这可能更容易阅读和推理。然后你可以这样做:

    def tab_is_valid(tab, valid_size=3):
        ''' is an individual member valid'''
        return len(tab) == valid_size and all(isinstance(n, int) for n in tab)
        
    def tabuleiro(tab):
        ''' is the whole structure valid '''
        return all((
             isinstance(tab, tuple),
             len(tab) == 3,
             all(tab_is_valid(t) for t in tab),
         ))
    
    
    tabuleiro(((1,0,1),(-1,1,0),(1,-1,-1)))
    # True
    
    tabuleiro(((1,0,1.6),(-1,1,0),(1,-1,-1)))
    # False
    
    tabuleiro(((1,0),(-1,1,0),(1,-1,-1)))
    #False
    
    tabuleiro(((1,0, 1),(-1,1,0),(1,-1,-1), (1, 1, 1)))
    # False
    

    【讨论】:

    • 感谢您的回答!仍在尝试使用单个函数找到更简单的方法。
    • @CateC 如果你想要一个函数,你可以简单地将位从函数复制到调用它的位置。如果只是阅读变得有点麻烦。
    • 函数tabuleiro()中我的值只能是(0,-1,1)怎么说?我已经尝试过了,但我知道出了点问题。 def tabuleiro(tab): return all((isinstance(tab, tuple) and len(tab) == 3 and \ all(isinstance(line,tuple) and len(line) == len(tab[0])) for line in tab) 和 len(tab[0]) == 3 and all((n in (0,1,-1) for line in tab for n in line))
    猜你喜欢
    • 1970-01-01
    • 2021-04-18
    • 2014-05-09
    • 2016-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-09
    相关资源
    最近更新 更多