簡體   English   中英

如何在 Python 中將壓縮列表擴展為完整列表?

[英]How to expand a compressed list into a full list in Python?

我有一個壓縮列表,如(可能更大):

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

我該怎么做才能將其擴展為完整列表?

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

我認為這是某種遞歸,但我不知道如何。 先感謝您

編輯:這是我已經為它編寫的一個函數,但它一直說語法錯誤。

def expandList(aList):
    """expand a list"""

    finalList = []

    for j in aList:

        if type(j) != type(list):
            tempList = []
            tempList.append(j)

            finalList.append(tempList)

        else:
            finalList.extend(expandList(j))

    return finalList

編輯:哎呀,我的意思是:

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

不是:

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

很抱歉有任何混淆。

你可能想試試這個,

l = [[[1, [2, 3], [3, 2]]], [[2, [1, 3], [3, 1]]], [[3, [1, 2], [2, 1]]]]
final_list = []
for k in l:
    for x in k:
        t = [x[0]]
        t.extend([i for i in x[1]])
        final_list.append(t)
        t = [x[0]]
        t.extend([i for i in x[2]])
        final_list.append(t)
print (final_list)

這產生,

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

假設您列出的確切輸入結構,帶有冗余list

big = [[[1, [2, 3], [3, 2]]], [[2, [1, 3], [3, 1]]], [[3, [1, 2], [2, 1]]]]
>>> [[a]+i for useless in big for a, *b in useless for i in b]
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

假設沒有冗余list的更清晰的輸入結構:

>>> big = [[1, [2, 3], [3, 2]], [2, [1, 3], [3, 1]], [3, [1, 2], [2, 1]]]
>>> [[a]+i for a, *b in big for i in b]
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

暫無
暫無

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

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