【问题标题】:How to append to a list the current -and not the final after iteration- state of another list? [duplicate]如何将另一个列表的当前状态而不是迭代后的最终状态附加到列表中? [复制]
【发布时间】:2021-07-10 13:46:31
【问题描述】:

这是我的代码的简化版本(我使用带有单次迭代的 for 循环,只是为了“模拟”我在原始代码中的正常循环):

import numpy as np

b=[]
for i in range(1):
    a=np.zeros([5])
    b.append(a)
    for j in range(1):
        for h in range(5):
            a[h]=h
        b.append(a)

b 的结果是:

[array([0., 1., 2., 3., 4.]), array([0., 1., 2., 3., 4.])]

我想要的b是:

[array([0., 0., 0., 0., 0.]), array([0., 1., 2., 3., 4.])]

【问题讨论】:

  • 嗨,欢迎来到 SO!请参阅here 获取有关格式化问题中代码的帮助。
  • 短版:第一次做b.append(a),只是引用a,而不是复制。因此,当您稍后使用 for h in range(5): a[h]=h 修改 a 时,您正在修改在索引 0 处 引用 的同一对象。阅读此答案以获取更多信息:List on python appending always the same value

标签: python list for-loop append iteration


【解决方案1】:
import numpy as np

b=[]
for i in range(1):
    a=np.zeros([5])
    b.append(a)
    for j in range(1):
        for h in range(5):
            a[h]=h
    b.append(a)
    # print(b)
    del b[0]
    # b.append(c)
    a=np.zeros([5])
    b.insert(0, a)
print(b)

试试这个输出是你所期望的:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 2015-12-18
    • 1970-01-01
    • 2014-05-28
    • 1970-01-01
    • 2022-10-25
    相关资源
    最近更新 更多