首页 > 解决方案 > 使用while循环对给定范围内的列表值求和

问题描述

我正在尝试对列表的值求和,但前提是列表值在特定范围内(例如在 5 和 -4 之间,或<= 0

如果我使用小于语句中的代码来检查列表值,则代码不起作用。

使用“<”时我哪里出错了?

我的示例数据:

# list
ulis = [ 5 , 4 , 4 , 3 , 1 , -2 , -3 , -5 , -7 , -7 ]
 #e      0   1   2   3   4    5    6    7    8    9

# list length
ulis_l  = len (ulis)

# to count total
total_1 = 0

# index nr list
e       = 0

# list of numbers used for total 
lprt    = []

while> = 0;一起使用 这有效:

print ( " # while command in progress " )
while ( ulis[e] >= 0) and ( e < ulis_l ):   
    total_1 = total_1 + ulis [e]
    lprt.append (ulis [e])
    e = e + 1
    print (total_1)

相同的代码,>= 0更改为<= 0不起作用,我不明白发生了什么:

print ( " # while command in progress " )
while ( ulis[e] <= 0) and ( e < ulis_l ):
    total_1 = total_1 + ulis [e]
    lprt.append (ulis [e])
    e = e + 1
    print (total_1)

我使用此代码检查输出:

print ( " " )
print ( " " )
print ( " # Total sum " )
print (total_1)
print ( " " )
print ( " # values used form org list ulis for Total sum " )
print (lprt)
print ( " " )
print ( " # ulis n org values " )
print ( ulis_l )

对于第一个循环,打印如下:

 # while command in progress 
5
9
13
16
17


 # Total sum
17

 # values used form org list ulis for Total sum
[5, 4, 4, 3, 1]

 # ulis n org values
10

但对于第二个循环,我看到:

 # while command in progress 


 # Total sum
0

 # values used form org list ulis for Total sum
[]

 # ulis n org values
10

标签: pythonwhile-loop

解决方案


不要使用while,它会在第一个错误结果处停止。您的循环不起作用,因为您测试的第一个值大于零,因此不满足循环的条件:

>>> ulis[0] <= 0
False

当不应将值添加到总数中时,您不想停止循环。您想忽略该值并继续下一个值。如果必须使用循环,则在语句while中使用单独的测试:if

while e < ulis_l:
    if ulis[e] <= 0:
        # You can use += here instead of total_1 = total_1 + ...
        total_1 += ulis[e]
        lprt.append(ulis[e])
    e = e + 1
    print(total_1)

那是因为您想访问列表中的每个值ulis测试它们是否需要包含在内。这是上述循环的演示:

>>> ulis = [5, 4, 4, 3, 1, -2, -3, -5, -7, -7]
>>> ulis_l = len(ulis)
>>> e = total_1 = 0
>>> lprt = []
>>> while e < ulis_l:
...     if ulis[e] <= 0:
...         # You can use += here instead of total_1 = total_1 + ...
...         total_1 += ulis[e]
...         lprt.append(ulis[e])
...     e = e + 1
...     print(total_1)
...
0
0
0
0
0
-2
-5
-10
-17
-24
>>> total_1
-24
>>> lprt
[-2, -3, -5, -7, -7]

for为此使用循环更好,更容易,您可以直接循环列表中的值:

for value in ulis:
    if value <= 0:
        lprt.append(value)
        total_1 += value
        print(total_1)

我将print()调用移到测试中,所以它只在我找到有效值时打印:

>>> lprt, total_1 = [], 0
>>> for value in ulis:
...     if value <= 0:
...         lprt.append(value)
...         total_1 += value
...         print(total_1)
...
-2
-5
-10
-17
-24

如果您只想对一系列符合特定条件的值求和,您还可以使用函数将生成器表达式放入函数调用中:sum()

total_1 = sum(value for value in ulis if value <= 0)

这是相同结果的更紧凑的表达式:

>>> sum(value for value in ulis if value <= 0)
-24

您的第一个示例有效,因为输入按降序排序;第一个小于 0 (-2)的值后面只能跟随更多小于 0 的值。如果您的输入很大,以这种方式限制迭代次数可能是一个非常聪明的主意。但是,您不需要while循环,您可以使用以下break语句

# first loop, values greater than 0
for value in ulis:
    if value <= 0:
        # input is sorted in descending order,
        # so all remaining values _will_ be smaller.
        # To save time, we can end the loop early.
        break

    # only sums values greater than 0
    total_1 += value
    lprt.append(value)

如果要在<= 0循环中使用此属性,则需要更改迭代列表的顺序。您可以使用此处的reversed()功能执行此操作:

# second loop, summing values smaller than or equal to 0 
for value in reversed(ulis):
    if value > 0:
        # input is iterated over in ascending order,
        # so all remaining values _will_ be greater than zero.
        # To save time, we can end the loop early.
        break

    # only sums values smaller than or equal to 0
    total_1 += value
    lprt.append(value)

当您将 a 添加print()到后一个版本时,您可以看到这些值以相反的顺序相加:

>>> lprt, total_1 = [], 0
>>> for value in reversed(ulis):
...     if value > 0:
...         break
...     total_1 += value
...     lprt.append(value)
...     print(total_1)
...
-7
-14
-19
-22
-24
>>> lprt
[-7, -7, -5, -3, -2]

如果您需要lprt正确的前向顺序,您可以通过使用负索引的完整切片再次反转排序:

lprt = lprt[::-1]   # reverse the lprt list

如果您有两个条件,例如值介于 5 和 -4 之间,并且输入列表非常大但仍然排序,那么您可以考虑使用二进制搜索来查找输入列表的开始和结束索引,然后使用range()type生成这两个点之间的索引。标准库为此提供了bisect模块

请注意,这确实意味着必须按升序而不是降序对值进行排序。

考虑到range()stop索引视为不包含在生成的索引中,因此如果您测试value >= -4and value <= 5,那么您希望使用bisect.bisect_right()查找值都大于 5 的第一个索引:

import bisect

# ascending order! ulis = ulis[::-1] 

start_index = bisect.bisect_left(ulis, -4)  # values >= -4
stop_index = bisect.bisect_right(ulis, 5)  # value <= 5

total_1 = sum(ulis[index] for index in range(start_index, stop_index))

推荐阅读