列表上的嵌套循环

时间:2018-07-06 21:53:01

标签: python python-3.x list loops for-loop

请参见下面的代码:

a=[1,2,3,4]
m=[0,0]
q=[]
for n in a:
    m[0]=n
    for n in a:
        m[1]=n
        q.append(m)
print(q)

所需的输出应为:

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

但是输出是:

[[4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4], [4, 4]]

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

您每次都将相同的列表追加到q,因此更改将影响q中的每个子列表。但是,有一种使用列表理解的方法可以轻松得多:

q = [[i, j] for i in a for j in a]

输出:

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

或使用 itertools

q = list(itertools.product(a, repeat=2))

输出:

[(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4), (3, 1), (3, 2), (3, 3), (3, 4), (4, 1), (4, 2), (4, 3), (4, 4)]

答案 1 :(得分:0)

在python中,列表作为引用存储在变量中,因此在每次迭代中更改m都会影响您附加到m列表中的所有q引用。

相反,请在添加之前用m复制m[:]

a=[1,2,3,4]
m=[0,0]
q=[]
for n in a:
    m[0]=n
    for n in a:
        m[1]=n
        q.append(m[:])
print(q)

这将输出:

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