使用range(i[0]、len(i)和

2024-03-28 20:00:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python是全新的。这是我自己学的。我总是在问问题之前用尽所有的资源。你知道吗

但我会给你看两套代码。一个做我想做的,另一个不是唯一的区别,我觉得,是如何设置范围。我不明白这种差别的意义。有人能解释一下吗?你知道吗

谢谢你。你知道吗

有效的代码

def geometric(lst):
    'checks whether the integers in list lst form a geometric sequence'
    if len(lst) <= 1:
        return True

    ratio = lst[1]/lst[0]
    for i in range(1, len(lst)-1):
        if lst[i+1]/lst[i] != ratio:
            return False
    return True

**不存在的代码**

def geometric(integerList):
    'checks whether the integers in list lst form a geometric sequence'
    if len(lst) <= 1:
        return True

    ratio = integerList[1]/integerList[0]
    for i in range (integerList[0], len(integerList))
        if lst[i+1]/lst[i] != ratio:
            return False
    return True

Tags: theintegers代码intruelenreturnif
3条回答
for i in range(1, len(lst)-1):
    ...

这段代码首先创建一个包含数字[1,2,3,...,len(lst)-1]的列表,然后通过在每次迭代中将i设置为列表中的值来循环这些值。你知道吗

for i in range (integerList[0], len(integerList))

这段代码实际上创建了一个包含以下数字的列表:

[integerList[0],integerList[0] + 1,integerList[0] + 2,...,len(integerList)]

这里的范围是从integerList[0]开始的,不是索引。如果integerList[0]大于len(integerList),则得到一个没有值的数组[]

然后在第二个函数中尝试使用lst,而实际上是在寻找integerList

正如Noelkd所说,第二个代码块中的range以列表第一个元素的值开始,而不是它的位置。你知道吗

如果我的列表是几何序列(1, 2, 4, 8, 16),那么第一个块的范围是

range(1, len(lst)-1) =
range(1, 5 - 1) =
range(1, 4) =
[1, 2, 3]

第二个街区的范围是

range(integerList[0], len(integerList)) =
range(1, 5) =
[1, 2, 3, 4]

如果我的序列不是以1开头,这种差异会变得更奇怪,比如序列(3, 9, 27)

第一个街区的范围是

range(1, len(lst)-1) =
range(1, 3 - 1) =
range(1, 2) =
[1]

第二个街区的范围是

range(integerList[0], len(integerList)) =
range(3, 3) =
[]

在第一种情况下,range(1, len(lst)-1)是一个列表

1, 2, 3, ..., len(lst)-1

在第二种情况下,它取决于第一个列表元素的值。如果integerList[0]是3,那么range()

3, 4, 5,  ..., len(lst)-1

if()语句的第一个调用比较integerList[4] / integerList[3],并忽略列表中的前三个元素。因此,代码只在integerList[0] == 1时有效

然而,还有两个陷阱:

  1. range()只接受整数作为元素。如果第一个元素是一个float,pyhon将抛出一个错误。

  2. 如果比率总是一个整数,您可以像这样比较比率是否相等。但是如果比率是一个浮动值,您可能会遇到麻烦:虽然两个比率在数学上相等,但计算机(由于其浮点运算)可能会计算出略微不同的值。最好使用

    import math ... if (math.fabs(lst[i+1]/lst[i] - ratio) < smallNumber)

其中smallNumer是一个非常小的数字适合你。你知道吗

顺便说一下:在第二段代码中,您使用了lst[],但我猜,这只是一个输入错误。你知道吗

相关问题 更多 >