为什么我的代码不能对列表中负数的值求和?

0 python while-loop

given_list3 = [7, 5, 4, 4, 3, 1, -2, -3, -5, -7]
total7 = 0
i = 0
while i <= len(given_list3) and given_list3[i] <= 0:
    total7 += givenlist3[i]
    i += 1
print(total7)
Run Code Online (Sandbox Code Playgroud)

该代码产生的结果为 0,我想得到:-2 + -3 + -5 + -7 = -17

j1-*_*lee 6

您可以使用理解:

given_list3 = [7, 5, 4, 4, 3, 1, -2, -3, -5, -7]
output = sum(x for x in given_list3 if x < 0)
print(output) # -17
Run Code Online (Sandbox Code Playgroud)

在当前代码中,您while甚至在第一次迭代之前就退出循环,因为第二个条件given_list3[i] <= 0为 false(因为第一项7大于0)。如果您想要一个工作版本,请尝试以下操作。(您还需要使用i < len(...)而不是 i <= len(...)。)

given_list3 = [7, 5, 4, 4, 3, 1, -2, -3, -5, -7]
total7 = 0
i = 0
while i < len(given_list3):
    if given_list3[i] <= 0:
        total7 += given_list3[i]
    i += 1
print(total7) # -17
Run Code Online (Sandbox Code Playgroud)