使用while循环在给定范围内汇总列表值

问题描述

我试图对列表的值求和,但前提是列表值在特定范围内(例如 5到-4

  • 使用while循环来解决这个问题。
  • 不要使用其他列表。

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

使用“

我的示例数据:

# list
ulis = [ 5,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,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

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)