【问题标题】:Python 3.8: Why is new_list being updated even though if statement is false?Python 3.8:为什么即使 if 语句为 false,new_list 也会被更新?
【发布时间】:2021-08-11 11:57:39
【问题描述】:

我是 python 的初学者,我想知道为什么在下面的代码中,new_list 在 for 循环的每次迭代后都会更新,即使 new_list 只应该在我的 if 条件为真时更新(这就是我想要的)。

my_sum = 0
first_list = [1, -2, 3, -4]
second_list = []
new_list = []

for num in first_list:
    second_list.append(num)
    if my_sum <= sum(second_list):
        my_sum = sum(second_list)
        new_list = second_list
    print(new_list)

输出:

[1]
[1, -2]
[1, -2, 3]
[1, -2, 3, -4]

但是,当我在 if 语句中移动 print 语句时,我会在每次 for 循环迭代结束后得到预期的结果:

my_sum = 0
first_list = [1, -2, 3, -4]
second_list = []
new_list = []

for num in first_list:
    second_list.append(num)
    if my_sum <= sum(second_list):
        my_sum = sum(second_list)
        new_list = second_list
        print(new_list) # Moved print statement inside if statement

输出:

[1]
[1, -2, 3]

有人可以解释为什么 new_list 在每次 for 循环迭代后更新,即使我只希望它在我的 if 条件为真时更新?

提前谢谢你!

【问题讨论】:

  • 在python中,列表赋值不会复制

标签: python for-loop if-statement variable-assignment


【解决方案1】:

您已在表达式 new_list = second_list 中将 new_list 别名为 second_list。基本上,在这条线之后它们都是同一个实体。相反,你想做new_list = second_list.copy()之类的事情。

【讨论】:

    猜你喜欢
    • 2018-06-25
    • 2019-05-20
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-26
    相关资源
    最近更新 更多