我正在尝试使用while
循环编写代码来汇总列表中的所有负数。我得到-10而不是-17。知道为什么吗?谢谢!
# 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)
各种事情都错了
-1 < 0
你应该做点什么
break
请注意,在python中,直接迭代值更常见
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
说实话,这不是写这个的最佳方式,但是如果你有一个排序列表,其中所有负数都在一边,那么这将起作用。
这个问题是你将i设置为0,即该列表中的7。所以你的while循环正在做的是,7 + -7 + -5 + -3 + -2 ...你可能想要启动i = -1,这样它添加的第一个对象是-7,它会给你你的期望的结果。
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]
虽然您的列表仅包含7,..- 7,但对“given_list3”的调用将在上述频谱上运行。允许负数在右边工作,而0和更高工作从左边工作。
如果你有一个List,其中负值是分散的,那么最好循环遍历每个单个对象,比较它是否<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]
在这种情况下,您不必担心从列表的另一侧开始。
你应该放一个given_list = [-2,-3,5,7,4,-5,4,3,1,-7]
total = 0
for num in given_list:
if num < 0:
total = total + num
print(total)
并逐步执行每一行。您将看到第一个增加的值是debugger,这是正数numbers[0]
。从那以后,它就像你期望的那样工作;它循环返回并添加数字,直到找到正数然后退出。
你可以像7
和higher order functions一样使用filter
来使你的代码更优雅,更不容易出错。
sum