Python:如何断言二维列表存在?

Python:如何断言二维列表存在?,python,Python,如何: 如果myList[k][m]: #逐步完成子集的每个项 而我

如何:

如果myList[k][m]:
#逐步完成子集的每个项
而我
上面的代码不起作用。我想检查该列表的第二维度是否存在(“m”)。

这个如何:

if myList[k][m]:
            # step through each item of the subset
            while i < len(myList[k][m]):
            ...

您可以使用try块:

for line in your_list:
    for element in line:
        assert element > whatever
或者:

try:
    for sublist in mylist:
        for item in sublist:
            pass # do stuff
except TypeError:
    pass # handle stuff here
你必须把它应用到你想要测试的每一个物体上

要检查“k”维度,请执行以下操作:

if hasattr(object, '__contains__'):
    pass # the object is iterable!
如果您只想检查第二个维度(“m”):


python中的列表与其他编程语言中的二维数组略有不同。要检查列表是否有第一个维度,可以尝试键入

if all([hasattr(sublist, '__contains__') for sublist in myList]):
    pass # myList[_] is iterable 
else:
    raise TypeError # handle stuff here
现在,在另一个列表或二维列表中的每个元素所在的列表中,列表中的每一行都可以有不同数量的列,这与

if len(myList) > 0:
    # Your Code here
使用Java或其他类似语言。因此,必须检查列表中每个元素的尺寸

Integer[][] array = new Integer[10][10]
这些都管用吗


编辑:添加检查以查看myList[k]是否为列表

如果
myList
myList
的某个元素不可编辑,则会引发异常。第一个解决方案和第二个解决方案:仍然获得“而mInteger[][] array = new Integer[10][10]
if len(myList) > 0:
    for i in range(len(myList)):
        if len(myList[i]) > 0:
            for j in range(len(myList[i])):
                # Do something with myList[i][j]
if myList[k] and isinstance(myList[k], list) and myList[k][m]:
     pass #do stuff

if len(myList) > k and isinstance(myList[k], list) and len(myList[k]) > m:
     pass #do stuff