我使用for循环对列表进行洗牌并将其附加到另一个空列表(列表A)。 我可以看到每个改组后的列表都是不同的,但列表A仅附加了最后一个改组后的列表的多个。
print('---------shuffle list-------------------------------------')
matr=[ ]
entry=[1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in range(9):
shuffle(entry )
print(entry )
matr.append(entry)
print(matr)
'''
results below:
---------shuffle list-------------------------------------
[3, 1, 7, 5, 8, 9, 2, 6, 4]
[5, 4, 6, 8, 1, 9, 7, 2, 3]
[6, 4, 7, 5, 1, 3, 2, 9, 8]
[4, 9, 8, 1, 7, 3, 6, 5, 2]
[5, 1, 9, 2, 8, 6, 4, 7, 3]
[3, 5, 1, 4, 2, 6, 8, 9, 7]
[1, 2, 4, 6, 7, 8, 3, 9, 5]
[4, 8, 1, 6, 7, 3, 5, 9, 2]
[6, 4, 2, 1, 9, 8, 3, 5, 7]
[[6, 4, 2, 1, 9, 8, 3, 5, 7], [6, 4, 2, 1, 9, 8, 3, 5, 7], [6, 4, 2, 1, 9, 8, 3, 5, 7], [6, 4, 2, 1, 9, 8, 3, 5, 7], [6, 4, 2, 1, 9, 8, 3, 5, 7], [6, 4, 2, 1, 9, 8, 3, 5, 7], [6, 4, 2, 1, 9, 8, 3, 5, 7], [6, 4, 2, 1, 9, 8, 3, 5, 7], [6, 4, 2, 1, 9, 8, 3, 5, 7]]
'''
它应该在每个改组列表的后面附加最后一个改组的列表。
答案 0 :(得分:0)
它们是相同的对象,所以您必须这样做,shuffle
是例外,您需要这样做:
matr=[]
entry=[1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in range(9):
entry = entry.copy()
shuffle(entry)
print(entry)
matr.append(entry)
print(matr)
输出:
[9, 7, 6, 4, 3, 2, 8, 5, 1]
[4, 3, 2, 8, 7, 1, 5, 9, 6]
[3, 9, 7, 4, 5, 8, 2, 1, 6]
[6, 1, 9, 5, 2, 3, 4, 7, 8]
[5, 4, 7, 9, 8, 2, 6, 3, 1]
[2, 3, 5, 8, 6, 7, 9, 4, 1]
[5, 4, 9, 8, 3, 6, 1, 7, 2]
[5, 1, 2, 3, 7, 8, 6, 9, 4]
[6, 8, 9, 2, 1, 5, 3, 7, 4]
[[9, 7, 6, 4, 3, 2, 8, 5, 1], [4, 3, 2, 8, 7, 1, 5, 9, 6], [3, 9, 7, 4, 5, 8, 2, 1, 6], [6, 1, 9, 5, 2, 3, 4, 7, 8], [5, 4, 7, 9, 8, 2, 6, 3, 1], [2, 3, 5, 8, 6, 7, 9, 4, 1], [5, 4, 9, 8, 3, 6, 1, 7, 2], [5, 1, 2, 3, 7, 8, 6, 9, 4], [6, 8, 9, 2, 1, 5, 3, 7, 4]]