python:参数化二维列表的大小是否满足我的要求

问题描述 投票:0回答:1

我想检查一下通过的二维列表是否符合我的要求。

def foo(twoDList):
 if len(twoDList) == 2:
   if len(twoDList[]) == 3:
     print("true")

然后在使用方法时:

a = [[1, 2, 3], [4, 5, 6]]
foo(a)  

应该是真的!我怎样才能修复 foo()

len(twoDList) == 2 和 all(len(sublist) == 3 对于twoDList 中的子列表)

python python-3.x list if-statement methods
1个回答
0
投票

len(twoDList[])
给了我一个语法错误,因为你必须在方括号之间传递一个索引。

我假设您希望每个子列表恰好包含三个元素:

def foo(twoDList):
    if len(twoDList) == 2:
        if all(len(sublist) == 3 for sublist in twoDList):
            print("true")

如果你想在twoDList不满足要求时引发错误,请使用

assert
关键字:

def foo(twoDList):
    assert(len(twoDList) == 2 and all(len(sublist) == 3 for sublist in twoDList))
    print("true")
© www.soinside.com 2019 - 2024. All rights reserved.