当前位置: 动力学知识库 > 问答 > 编程问答 >

Python: How to assert a two dimensional list exists?

问题描述:

How to:

if myList[k][m]:

# step through each item of the subset

while i < len(myList[k][m]):

...

Above is not working. I want to check if the 2nd dimension of that list exists (the 'm').

网友答案:

You can use a try block:

try:
    for sublist in mylist:
        for item in sublist:
            pass # do stuff
except TypeError:
    pass # handle stuff here

Alternatively:

if hasattr(object, '__contains__'):
    pass # the object is iterable!

You will have to apply that to every object you want to test the iterable-ness of.

To check the 'k' dimension:

if hasattr(myList, '__contains__'): # this is sufficient
    pass # myList is iterable
else:
    raise TypeError

If you just want to check the second dimension (the 'm'):

if all([hasattr(sublist, '__contains__') for sublist in myList]):
    pass # myList[_] is iterable 
else:
    raise TypeError # handle stuff here
网友答案:

How about this:

for line in your_list:
    for element in line:
        assert element > whatever
网友答案:
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

Will any of those work ?

Edit: Added check to see if myList[k] is a list

网友答案:

Lists in python are slightly different than a two dimensional array in other programming languages. to check if the list has a first dimension you can try typing

if len(myList) > 0:
    # Your Code here

Now in a list in which each element in another list or a two dimensional list - Each row in the list can have a variable number of columns which is not the same as saying

Integer[][] array = new Integer[10][10]

in Java or another similar language. Hence you must check the dimensions of each of the elements in the list.

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]
分享给朋友:
您可能感兴趣的文章:
随机阅读: