Python在列表追加后跳转到另一个变量

时间:2017-01-30 09:53:46

标签: python

我想向运营商分配金额,但是在追加循环跳转后不要向另一个变量追加:

op1 = []
op2 = []
op3 = []
operators = [op1, op2, op3]
unsigned_loans = [100, 200, 300, 400]

sum_of_all_loans = 0

for loan in unsigned_loans:
    sum_of_all_loans += loan

per_user_amount = sum_of_all_loans / len(operators)

unsigned_loans.sort()



for oper in operators:
    for loan in unsigned_loans:
        print(loan)
        if sum(oper) < per_user_amount:
            oper.append(loan)
        unsigned_loans.remove(loan)
    print(oper)
输出应该是:

 op1=[100, 200] op2=[300] op3=[400]

但现在显示

op1=[100, 300] op2=[200] op3=[400]

1 个答案:

答案 0 :(得分:4)

你是iterating over a list and modifying it at the same time,这总是会引发错误。如果你没有remove循环中列表中的任何内容,那么它将更具可预测性。立即修复是迭代副本,因为链接页面在接受的答案中建议。

或者,您可以稍微调整一下逻辑,例如总是以最低的当前金额向经营者提供贷款:

for loan in unsigned_loans:
     oper = min(operators, key=sum)
     oper.append(loan)

这样会导致[100, 400], [200], [300]