【问题标题】:Append overwrites every element with last appended value (Python)Append 用最后一个附加值覆盖每个元素(Python)
【发布时间】:2023-03-17 22:59:01
【问题描述】:

我想准备包含所有可能的参数组合的列表列表,这些参数组合将用于蛮力搜索。参数组合应如下所示:

[0, 0, 1]
[0, 0.2, 0.8]
[0.2, 0, 0.8]
...
[0.4, 0.4, 0.2]
...
[1, 0, 0]

生成这些列表的代码运行良好 - 在每次迭代中打印 weights_temp 都会返回正确的结果。但是附加有一些问题。当我打印 weights 时,我得到的只是这个(最后一个 weights_temp 值而不是其他元素):

[1.0, 0.0, 0.0]
[1.0, 0.0, 0.0]
...
[1.0, 0.0, 0.0]
...
[1.0, 0.0, 0.0]

这是我的代码:

step = 0.2

weights_temp = [0, 0, 1]
weights = [weights_temp]

i = 1

while weights_temp != [1, 0, 0]:
    # decrease gamma
    weights_temp[2] = 1 - i * step

    for j in xrange(0, i + 1):
        # increase alpha, decrease beta
        weights_temp[0] = j * step
        weights_temp[1] = abs(1 - weights_temp[2]) - j * step

        weights.append(weights_temp)

        print weights_temp

    i += 1

有人知道如何解决这个问题吗?

提前谢谢你

【问题讨论】:

  • weights.append(weights_temp) 每次都附加相同的内容,因为据我所知, weights_temp 是数据的引用/指针。即,您不是追加新列表并更改该列表,而是每次都追加相同的引用并更改该引用处的数据。如果您在追加时打印weights,您可能会看到每个列表每次都在更新

标签: python python-2.7


【解决方案1】:

继续我的评论,而不是添加参考,每次添加列表理解时都创建一个新列表。

weights.append([item for item in weights_temp])

例子:

>>> temp = [1,2,3]
>>> holder = [temp]
>>> holder
[[1, 2, 3]]
>>> temp[0] += 1
>>> holder
[[2, 2, 3]]
>>> holder.append([item for item in temp])
>>> holder
[[2, 2, 3], [2, 2, 3]]
>>> temp[0] +=1
>>> holder
[[3, 2, 3], [2, 2, 3]]

【讨论】:

    【解决方案2】:
    for s in arr:
    li.append(
        {"id":s.get("InstanceId"),"Message":s.get("Status").get("Message") }
     )
    

    【讨论】:

    • 欢迎。请务必包含解释,而不仅仅是代码。
    猜你喜欢
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 2015-11-10
    • 2021-05-16
    • 2010-12-11
    • 2020-04-25
    • 1970-01-01
    相关资源
    最近更新 更多