索引列表超出范围

index list out of range

以下代码的要点是采用 ab 和列表变量的范围,并将建议范围内的数字与列表数字进行比较。

如果列表中的数字大于 a 且小于 b,则将其计为一个。 none,这不算什么。

def between(lst, a, b):
    i=len(lst)
    count = 0
    for n in range(a, b):
        if lst[n] > a and lst[n] < b:
            count = count + 1
        else:
            count = count + 0                   
    return count
    
# TESTS 

print("********************")
print("Starting the test:")
    
print("********************")
print("Counting over [1, 2, 3, 4] with a = 0, b = 5")
ans = between([1, 2, 3, 4], 0, 5)
if ans == 4:
    print("CORRECT: Very good, there are 4 elements between a = 0 and b = 5 in [1, 2, 3, 4]")
else:
    print("WRONG: There are 4 elements between a = 0 and b = 5 in [1, 2, 3, 4] but the code returned", ans)

print("********************")
print("Counting over [-5, 20, 13, 0] with a = 200, b = 300")
ans = between([-5, 20, 13, 0], 200, 300)
if ans == 0:
    print("CORRECT: Very good, there are no elements between a = 200 and b = 300 in [-5, 20, 13, 0]")
else:
    print("WRONG: There are no elements between a = 200 and b = 300 in [-5, 20, 13, 0] but the code returned", ans)
    
print("********************")
print("Counting over [-5, 20, 13, 0] with a = -10, b = 5")
ans = between([-5, 20, 13, 0], -10, 5)
if ans == 2:
    print("CORRECT: Very good, there are 2 elements between a = -10 and b = 5 in [-5, 20, 13, 0]")
else:
    print("WRONG: There are 2 elements between a = -10 and b = 5 in [-5, 20, 13, 0] but the code returned", ans)

print("********************")    
print("Tests concluded, add more tests of your own below!")
print("********************")

您的 between 功能有误。您可以使用调试器找到它(例如,参见 this question)。

正确的版本:

def between(lst, a, b):
    count = 0
    for elem in lst:
        if a <= elem <= b:
            count = count + 1                 
    return count

更短(更快)的版本:

def between(lst, a, b):
    return sum(1 for elem in lst if a <= elem <= b)