返回空列表-1

时间:2014-05-21 16:43:27

标签: python python-3.x

def findMiniRow(numlst):
    x = []
    for lst in numlst:
        x.append(sum(lst))
        m = min(x)
    return [i for i, j in enumerate(x) if j == m]

输出:

>>> findMiniRow([])
[]
>>> findMiniRow([[3.99,-12.5,8.61],[0],[-3,-5,-7]])
[2]
>>> findMiniRow([[1,2,3],[-100],[10,-30.5,8]])
[1]
>>> findMiniRow([[10,20],[100,200],[8,7,6,5],[13],[8,9,10]])
[3]
>>> 

当findMiniRow([])我希望输出为-1。我尝试了If!= [] / Else返回-1但似乎无法使其工作。

1 个答案:

答案 0 :(得分:1)

处理这一特殊情况的最简单方法是预先做好准备:

def findMiniRow(numlst):
    if not numlst:
        return -1
    x = []
    for lst in numlst:
        x.append(sum(lst))
        m = min(x)
    return [i for i, j in enumerate(x) if j == m]

或者,如果你真的想在最后使用三元组:

def findMiniRow(numlst):
    x = []
    for lst in numlst:
        x.append(sum(lst))
        m = min(x)
    return [i for i, j in enumerate(x) if j == m] if numlst else -1

然后您无需创建x