如何在 python 中包含范围中的最后一个元素?

问题描述 投票:0回答:3

我正在使用 for 循环添加列表中的所有元素,但是当我索引 (x[-1]) 最后一个元素时,它仍然不包括在内。例如:

x=[3,4,5,6]
total=0
for i in range(x[0],x[-1]):
    total= total + i
print(total)

我正在寻找的答案是 18,但是当我运行它时,它返回 12。(它仍然不包括最后一个元素)。我知道 range 函数可以做到这一点,但是有没有办法仍然包含最后一个元素?我必须使用不同的功能吗?我做错了什么?

python list for-loop range
3个回答
1
投票

以下是适合您使用的三种解决方案

    x=[3,4,5,6]
    total=0

    #solution 1 :
    total =sum(x)

    #solution 2
    for i in x:
        total= total + i
    print(total)

    #solution 3
    for i in range(0,len(x)):
        total= total + x[i]
    print(total)

0
投票

使用您的代码:

x=[3,4,5,6]
total=0
for i in x:
    total= total + i
print(total)

0
投票

在您的代码中,取消引用的 for 循环如下所示:

for i in range(3,6):

因此它以 i 值为 3,4 和 5 进行循环。 要解决这个问题,如果列表中的数字始终以 1 递增,则可以在范围中添加 +1,但在我看来,这不是一个好的代码。

for i in range (x[0],x[-1]+1):

我建议您首先不要取消引用范围函数中的列表,更好的选择是使用 len():

for i in range(len(x)):
   total = total + x[i]

这样您就可以确保循环遍历整个列表并引用每个元素

编辑:请注意,这更多是出于解释原因,最简洁的方法如上所述:

for i in x:
   total += i
© www.soinside.com 2019 - 2024. All rights reserved.