请参见下面的代码:
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]]
有什么想法吗?
答案 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]]