为什么我的循环只打印列表长度的一半?

2024-10-03 02:41:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个有60个元素的列表,现金流。我正在构建一个新列表ListNPV,其中每个元素都是使用原始现金流中每个元素的等式的结果。在将总和添加到新列表后,我从原始现金流中删除一个元素。在

当我运行这个程序时,它正好完成了列表的一半,所以有30个值。把结果从45/30翻了一番。我要0/60。使用顶棚。在

 for payment in CashFlow:  
    NPV = 0 
    for i in range(len(CashFlow)):    
        NPV += CashFlow[i] / (1+MonthlyInterest)**i
        NPV = round (NPV, 0)
    ListNPV.append(NPV)
    CashFlow.remove(payment)
print 'CashFlow = ', CashFlow
print 'ListNPV =', ListNPV

Tags: in程序元素列表forpaymentprint总和
2条回答

由于以下线路

 CashFlow.remove(payment)

线以上影响现金流。删除这一行,所有的迭代都将完成。之后,您可以单独删除现金流列表。在

the python docs开始,不应更改正在迭代的列表:

If you need to modify the sequence you are iterating over while inside the loop (for example to duplicate selected items), it is recommended that you first make a copy. Iterating over a sequence does not implicitly make a copy.

在本例中,您甚至不使用循环变量payment,因此您可以稍微清理一下循环。这应该是有效的:

N = len(CashFlow)
for j in range(N):
    NPV = 0 
    for i in range(j, N):
        NPV += CashFlow[i] / (1+MonthlyInterest) ** (i - j)
        NPV = round (NPV, 0)
    ListNPV.append(NPV)

print 'CashFlow = ', CashFlow
print 'ListNPV =', ListNPV

相关问题 更多 >