我正在尝试仅对以下列表中的正数求和,但我的代码没有做到这一点,对哪一行不正确的任何注释都很棒!
given_list3 = [5,4,4,3,1,-2,-3,-5]
total5 = 0
p = 0
for p in given_list3:
if given_list3[p] > 0:
total5 += given_list3[p]
p += 1
print(total5)
我得到的输出为12,应该是17。
我正在尝试仅对以下列表中的正数求和,但我的代码没有做到这一点,对哪一行不正确的任何注释都很棒!
given_list3 = [5,4,4,3,1,-2,-3,-5]
total5 = 0
p = 0
for p in given_list3:
if given_list3[p] > 0:
total5 += given_list3[p]
p += 1
print(total5)
我得到的输出为12,应该是17。
使用“ p in”时,您将在列表中得到所有p。这不是列表中的索引。 如果要在列表中使用索引,请使用“ while”