簡體   English   中英

如何組合不同列表中的元素

[英]How to combine elements in different lists

我嘗試使用下面的代碼,以兩個列表之間的元素結合起來。

隨着輸入:

nested_array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

我想要輸出:

[[1, 4, 5, 6], [2, 4, 5, 6], [3, 4, 5, 6], [1, 7, 8, 9], ... [6, 7, 8, 9]]

我嘗試使用以下,但它似乎並沒有在我想要的格式輸出也。

你能幫忙嗎?

def unique_combination(nested_array):
    try:
        for n1, array in enumerate(nested_array):
            for element in array:
                a = [element], list(nested_array[n1+1])
                print(a)
    except IndexError:
        pass

此外,而不是使用打印(),我試圖用操作返回。 但是隨着操作返回,它只返回一個輸出。 我編碼正確嗎?

不知道完整的期望輸出,這看起來像它得到你想要的東西。 請注意,這可以使用列表推導式寫在一行中,但這是令人討厭的一行。

nested_array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

for list_index in range(len(nested_array) - 1):
    for marcher_index in range(list_index + 1, len(nested_array)):
        for ele in nested_array[list_index]:
            print([ele] + nested_array[marcher_index])

輸出:

[1, 4, 5, 6]
[2, 4, 5, 6]
[3, 4, 5, 6]
[1, 7, 8, 9]
[2, 7, 8, 9]
[3, 7, 8, 9]
[4, 7, 8, 9]
[5, 7, 8, 9]
[6, 7, 8, 9]

嘗試這個:

flatten_list = lambda ls: [item for sublist in ls for item in sublist]

nested_array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
unique_combination = [[i]+nested_array[j]  for j in range(1,len(nested_array)) 
                                           for i in flatten_list(nested_array[:j])]
print(unique_combination)

輸出

[[1, 4, 5, 6],
 [2, 4, 5, 6],
 [3, 4, 5, 6],
 [1, 7, 8, 9],
 [2, 7, 8, 9],
 [3, 7, 8, 9],
 [4, 7, 8, 9],
 [5, 7, 8, 9],
 [6, 7, 8, 9]]

暫無
暫無

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

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