Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么代码不只是对正数求和?_Python_Loops_For Loop - Fatal编程技术网

Python 为什么代码不只是对正数求和?

Python 为什么代码不只是对正数求和?,python,loops,for-loop,Python,Loops,For Loop,我试图对下面列表中的正数求和,但我的代码没有这样做,任何不正确的注释都会很好 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都会显示出来

我试图对下面列表中的正数求和,但我的代码没有这样做,任何不正确的注释都会很好

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”

given_list3 = [5,4,4,3,1,-2,-3,-5]
total5 = 0
p = 0

while p < len(given_list3):
    if given_list3[p] > 0:
        total5 += given_list3[p]
    p += 1

print(total5)
给定清单3=[5,4,4,3,1,-2,-3,-5]
总计5=0
p=0
而p0:
总计5+=给定的清单3[p]
p+=1
打印(共5页)
基于值的循环 当在
列表上迭代时,循环变量一次保存列表中的一个值,而不是列表的索引。下面将打印所有值,而不是它们的索引

for p in given_list3:
    print(p)
因此,您需要的是(将
p
重命名为
value


基于索引的循环 如果您想使用索引访问值,如
给定的\u list3[i]
,则需要设置
i
以获取从0到列表长度的所有值,您可以使用
范围进行访问

for i in range(len(given_list3)): 
    if given_list3[i] > 0:
        total5 += given_list3[i]
你能行

sum([i for i in given_list3 if i > 0])

它们都将输出

17
代码中阻止聚合数字的行是

for p in given_list3: 
    if given_list3[p] > 0: 
你可以这样做

for p in given_list3: 
    if p > 0: 


您使用p作为索引,而p作为值或项。(您刚才向我们清楚地显示了C++或java LOL)。 这是你应该做的

given_list3 = [5,4,4,3,1,-2,-3,-5]
total5 = 0
for p in given_list3:
    if p > 0:
        total5 += p
print(total5)

p
是值,而不是索引。还有
sum(如果x>0,在给定的列表中x代表x)
?@hansolo:你基本上是说“除了第一行以外的所有行都错了”。但也存在一定程度的错误。是的,但用户已经给出了答案。只是指出一个更简单的版本。这就是全部:)帕特里克·庄是一位新的贡献者。我想我正在努力学习python。为什么不让他按照自己的节奏学习呢。用python方法可能不是最好的理解方法。既然可以直接使用p作为值,为什么还要使用p作为索引呢?非常好!所以第5行是不正确的,这是一个最小的变化。@azro使用p作为索引是发问者正在尝试的。那么为什么不帮助他理解他自己的密码呢?@Mace他说的哪个词让你这么说?@azro:因为它在正确的地方纠正了OP的密码。如果您要建议不同的代码,请在列表中使用
sum
提供答案。
for p in given_list3: 
    if p > 0: 
for p in len(given_list3): 
    if given_list3[p] > 0: 
given_list3 = [5,4,4,3,1,-2,-3,-5]
total5 = 0
for p in given_list3:
    if p > 0:
        total5 += p
print(total5)