循环范围(0) [英] Looping over range(0)

查看:45
本文介绍了循环范围(0)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

函数如下:

def is_sorted(L):
    """ (str) -> Bool

    Return True iff the L is sorted in nondecreasing order. Otherwise, return
    False.

    >>> is_sorted([1, 2, 3, 3])
    True
    >>> is_sorted([3, 2, 1, 3])
    False
    """
    if len(L) == 0:
        return False

    for i in range(len(L) - 1):
        if L[i] > L[i + 1]:
            return False

    return True

然后我在一个包含一个字符的列表上执行它,它返回 True.但是,我预计会收到列表索引超出范围错误".谁能解释一下它为什么会这样?

Then I executed it on a list with one character and it returns True. However, I expected to receive 'list index out of range error'. Could anyone explain why does it behave in such way?

推荐答案

range(a, b, s)[a, a+s, a+2*s..., x] 其中 x .

所以 range(0) ->range(0,0,1) 生成一个空的 list.这意味着 for 循环的内部被跳过,返回 True.

So range(0) -> range(0,0,1) generates an empty list. This means the inside of the for loop is skipped which returns True.

这篇关于循环范围(0)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆