簡體   English   中英

如何在列表python中交換列表中的項目

[英]How to swap items in a list within a list python

我試圖隨機交換列表中每個列表中的 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 mylist


print(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]]))

每當我運行它並打印出結果時,它只會再次打印出我的輸入。

有誰知道我的代碼有什么問題?

謝謝。

您的代碼與大約一半的子列表執行交換。 我想知道這種行為的原因是什么*(見下文)。

如果你像這樣重寫交換部分:

    i = mylist[x].index(to_swap[0])
    j = mylist[x].index(to_swap[1])
    mylist[x][i], mylist[x][j] = mylist[x][j], mylist[x][i]

那么它的工作原理。

更新:

無需訪問作業右側的列表,因為我們已經知道這些值,因此更新后的答案將是:

    i = mylist[x].index(to_swap[0])
    j = mylist[x].index(to_swap[1])
    mylist[x][i], mylist[x][j] = to_swap[1], to_swap[0]

*更新2:

上述行為是由於在多個賦值中,左側的表達式從左到右一個一個地求值。 這意味着 OP 的代碼在index(to_swap[0]) < index(to_swap[1])

示例:第一個子列表[8, 5, 4, 1, 3, 9, 7, 6, 2]值 5 和 6。 首先,程序會做

mylist[x][mylist[x].index(5)] = 6

將列表修改為[8, 6, 4, 1, 3, 9, 7, 6, 2] 二、程序會做

mylist[x][mylist[x].index(6)] = 5

將其修改回[8, 5, 4, 1, 3, 9, 7, 6, 2]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM