简体   繁体   English

只求列表中负数的总和

[英]to find the sum of only the negative numbers of the list

when i used for loop for length of the list I got the correct answer.But when I use for loop for I in range list: I got the correct wrong answer enter image description here the first Image shows when value of i is taken.the second image shoes when for loop is take for length of list.what's the problem here?当我为列表长度使用 for 循环时,我得到了正确的答案。但是当我在范围列表中使用 for 循环时:我得到了正确的错误答案在此处输入图像描述,第一张图像显示何时获取 i 的值。第二张图片鞋当 for 循环用于列表长度时。这里有什么问题? enter image description here在此处输入图像描述

You can use the filter (to filter negative numbers) and then sum them -您可以使用filter (过滤负数)然后对它们sum -

>>> p = [1,2,-3,4,-4,5,6]
>>> sum(filter(lambda x: x < 0, p))
-7

you are indexing the list like this p[1],p[2],p[-3]...您正在索引这样的列表 p[1],p[2],p[-3]...

instead you should iterate through the values相反,您应该遍历这些值

p = [1,2,-3,4,-4,5,6]
t = 0
for i in p:
    if i < 0:
        t += i
print(t)

or use range(len(p)):或使用范围(len(p)):

p = [1,2,-3,4,-4,5,6]
t = 0
for i in range(len(p)):
    if p[i] < 0:
        t += p[i]
print(t)

This is the python code you had in the posted picture.这是您在发布的图片中拥有的 python 代码。

p = [1,2,-3,4,-4,5,6]
t = 0
for i in p:
   if p[i] < 0:
     t+=p[i]
print(t)

when you use for i in p , we iterate through the list unlike accessing the list values by their index If you print each of the value during the loop当您for i in p ,我们会遍历列表,这与通过索引访问列表值不同如果您在循环期间打印每个值

for i in p:
     print(i)
output: 
1
2
-3
4
-4
5
6

Also note that p[-3] indicates 3rd element from tail of the list so the values p[i] in your code are p[1],[2],p[-3],p[4],p[-4],p[5],p[6] equivalent to 2,-3,-4,-4,5,6 giving you a result of ((-3)+(-4)+(-4)) = -11另请注意, p[-3]表示列表尾部的第三个元素,因此代码中的值p[i]p[1],[2],p[-3],p[4],p[-4],p[5],p[6]相当于2,-3,-4,-4,5,6给你一个结果((-3)+(-4)+(-4)) = -11

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM