我試圖隨機(jī)交換列表中每個列表中的 2 個項目,其中要交換的項目不在另一個列表中。這是我的代碼import random def swap(mylist): remain = [[1, 2], [4], [], [8, 2], [1, 4], [5, 2, 1], [], [9, 5], [7]] for x in range(0, 9): remaining = set(mylist[x]) - set(remain[x]) to_swap = random.sample(remaining, 2) mylist[x][mylist[x].index(to_swap[0])], mylist[x][mylist[x].index(to_swap[1])] = mylist[x][mylist[x].index(to_swap[1])], mylist[x][mylist[x].index(to_swap[0])] return mylistprint(swap([[8, 5, 4, 1, 3, 9, 7, 6, 2], [9, 3, 5, 6, 4, 7, 1, 2, 8], [7, 3, 2, 5, 4, 1, 9, 6, 8], [2, 1, 3, 8, 6, 9, 5, 7, 4], [1, 2, 3, 5, 7, 4, 9, 8, 6], [6, 9, 3, 1, 7, 4, 2, 8, 5], [1, 2, 7, 4, 3, 8, 5, 9, 6], [3, 7, 8, 4, 1, 5, 9, 6, 2], [4, 2, 6, 5, 7, 1, 9, 3, 8]]))每當(dāng)我運(yùn)行它并打印出結(jié)果時,它只會再次打印出我的輸入。有誰知道我的代碼有什么問題?
添加回答
舉報
0/150
提交
取消