如何将列表附加到列表?

How to append a list to a list?

我正在尝试将一个列表附加到另一个列表中,但我似乎无法让它工作。

这是代码。当我 运行 它并为 while 循环的每次迭代打印 Q 我得到类似 [2,3] [2] [3,4] 等的东西。我想将这些列表附加到列表 my_Q 通过 my_Q.append(Q)。然而,这个 returns 我这个: my_Q = [0, [], [], [] ]

import random

#Matrix Input
M = 10**3

G = [   [M, 5, 9, M],
        [M, M, 1, 10],
        [M, M, M, 4],
        [M, M ,M, M]    ]

#Initialize
Q = [1]
l = [0, M, M, M]
A = [1, 2, 3, 4]
iter = 0

#For display
my_v = [0]
my_Q = [1]

#Algorithm
while Q:        #Stop conditions
    
    iter += 1

    #Step 2:
    v = random.choice(Q)
    Q.remove(v)

    #Step 3:
    for w in A:
        l_new = min(l[w-1], l[v-1] + G[v-1][w-1])
        if l_new != l[w-1]:
            if w not in Q:
                Q.append(w)
            l[w-1] = l_new

    #Save for display
    my_v.append(v)
    
    print(Q)
    my_Q.append(Q)

print(my_Q)

您有一个 aliasing 问题。 Python 混淆了你的实现,但是将一个列表附加到另一个列表只会添加一个引用,而不是列表的值。

试试这个简单的代码:

l = []
a = [1, 2]
l.append(a)
a.remove(1)
l.append(a)
print(l)

输出

[[2], [2]]

在这个例子中,你期待像 [[1, 2], [2]] 这样的东西,但是因为 a 只是 l 中的一个引用,调用 1 上的 remove 会把它从a 外部变量及其在列表中的引用 l.

您可以 import copy 并附加列表的深层副本。

import copy
import random

# Matrix Input
M = 10 ** 3

G = [[M, 5, 9, M],
     [M, M, 1, 10],
     [M, M, M, 4],
     [M, M, M, M]]

# Initialize
Q = [1]
l = [0, M, M, M]
A = [1, 2, 3, 4]
iter = 0

# For display
my_v = [0]
my_Q = [1]

# Algorithm
while Q:  # Stop conditions

    iter += 1

    # Step 2:
    v = random.choice(Q)
    Q.remove(v)

    # Step 3:
    for w in A:
        l_new = min(l[w - 1], l[v - 1] + G[v - 1][w - 1])
        if l_new != l[w - 1]:
            if w not in Q:
                Q.append(w)
            l[w - 1] = l_new

    # Save for display
    my_v.append(v)

    print(Q)
    my_Q.append(copy.deepcopy(Q))

print(my_Q)

输出

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

我不一定知道你的算法试图完成什么,但这会在每次迭代时将 Q 的当前状态附加到 my_Q,并且不允许调用 remove 修改列表中已有的 Q 的实例。

如果您不想从副本中使用深度复制,您可以使用切片符号来制作副本。

# my_Q.append(copy.deepcopy(Q))
my_Q.append(Q[:])