首页 > 解决方案 > 如何组合不同列表中的元素

问题描述

我正在尝试使用下面的代码来组合两个列表之间的元素。

输入:

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

另外,我没有使用 print(),而是尝试使用操作返回。但是对于返回操作,它只返回一个输出。我编码正确吗?

标签: python

解决方案


在不知道所需的全部输出的情况下,这看起来像是为您提供了您想要的东西。请注意,这可以使用列表推导式写在一行中,但这是令人讨厌的一行。

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]

推荐阅读