如何找出索引是否在嵌套列表中

时间:2018-11-09 06:41:46

标签: python

from typing import List

def is_sink(m: List[List[int]], c: List[int]) -> bool:
    """
    Returns True if and only if c is a sink in m.

    Examples (note some spacing has been added for human readablity)
    >>> m = [[1,2,3],
             [2,3,3],
             [5,4,3]]
    >>> is_sink(m, [0,0])
    True
    >>> is_sink(m, [2,2])
    True
    >>> is_sink(m, [3,0])
    False
    >>> m = [[1,2,3],
             [2,1,3],
             [5,4,3]]
    >>> is_sink(m, [1,1])
    True
    """
    try:
        return if c in m
    except IndexError:
        return False

我不确定尝试部分,但是我确实找出了例外部分

1 个答案:

答案 0 :(得分:1)

您尝试使用if语句返回的方式是错误的,这是您可以使用的方式。

def is_sink(m: List[List[int]], c: List[int]) -> bool:
    try:
        val = m[c[0]][c[1]]
        return True
    except IndexError:
        return False


m = [[1,2,3],[2,3,3],[5,4,3]]
print(is_sink(m, [1,1]))
print(is_sink(m, [3,0]))

输出:

True
False