Python使用While循环求和负值

问题描述投票：0回答：4

``````# sum all the negative numbers using a while loop
given_list3 = [7, 5, 4, 4, 3, 1, -2, -3, -5 ,-7]
total6 = 0
i = 0
while -1 < 0:
total6 += given_list3[i]
i += -1
if given_list3[i] > 0:
break
print(total6)
``````
python
4个回答
1

• qazxsw poi没有意义，它不会终止
• 当你找到第一个负面元素时，你`-1 < 0`

``break``

``````index = 0

while index < len(lst):
value = lst[index]

if value > 0:
continue

total += value

index += 1
``````

``````for value in lst:
if value >= 0:
total += value
``````

0

``````total = sum([x for x in lst if x >= 0])
``````

``````# sum all the negative numbers using a while loop
given_list3 = [7, 5, 4, 4, 3, 1, -2, -3, -5 ,-7]
total6 = 0
i = -1
while -1 < 0:
total6 += given_list3[i]
i += -1
if given_list3[i] > 0:
break
print(total6)
``````

``````List items:  [7, 5, 4, 4, 3, 1, -2, -3, -5 ,-7]
Positions:   [0][1][2][3][4][5] [6] [7] [8] [9]

List items:  [  7,  5,  4,  4,  3,  1, -2, -3, -5 ,-7]
From Reverse:[-10][-9][-8][-7][-6][-5][-4][-3][-2][-1]
``````

0

``````List:     [   7,  5,  4,  4,  3,  1, -2, -3, -5 ,-7, 7, 5, 4, 4, 3, 1, -2, -3, -5 ,-7]
Positions:[ -10][-9][-8][-7][-6][-5][-4][-3][-2][-1][0][1][2][3][4][5] [6] [7] [8] [9]
``````

0

``sum``