在python中创建递归嵌套列表

时间:2018-08-23 10:14:23

标签: python list recursion nested

我的初始列表在Python中是这样的。

list_1 = [ ['A', 'B', 'C'], [1, 2, 3], ['X', 'Y', 'Z'] ]

我需要像这样将其转换为一个...

    return = [
['A', 1, 'X'], ['A', 1, 'Y'], ['A', 1, 'Z'],
['A', 2, 'X'], ['A', 2, 'Y'], ['A', 2, 'Z'],
['A', 3, 'X'], ['A', 3, 'Y'], ['A', 3, 'Z'],
['B', 1, 'X'], ['B', 1, 'Y'], ['B', 1, 'Z']... ]

问题是我不知道list_1中有很多子列表。 例如,list_1可能类似于...

list_1 = [ ['A','B','C'], [1, 2, 3], ['X','Y','Z'], [6,7,8] ]

2 个答案:

答案 0 :(得分:4)

使用itertools.product

import itertools

itertools.product(*list_1)

输出(包装在list中)

[('A', 1, 'X'),
 ('A', 1, 'Y'),
 ('A', 1, 'Z'),
 ('A', 2, 'X'),
 ('A', 2, 'Y'),
 ('A', 2, 'Z'),
 ('A', 3, 'X'),
 ('A', 3, 'Y'),
 ('A', 3, 'Z'),
 ('B', 1, 'X'),
 ('B', 1, 'Y'),
 ('B', 1, 'Z'),
 ('B', 2, 'X'),
 ('B', 2, 'Y'),
 ('B', 2, 'Z'),
 ('B', 3, 'X'),
 ('B', 3, 'Y'),
 ('B', 3, 'Z'),
 ('C', 1, 'X'),
 ('C', 1, 'Y'),
 ('C', 1, 'Z'),
 ('C', 2, 'X'),
 ('C', 2, 'Y'),
 ('C', 2, 'Z'),
 ('C', 3, 'X'),
 ('C', 3, 'Y'),
 ('C', 3, 'Z')]

获取列表列表

list(map(list, itertools.product(*list_1)))

答案 1 :(得分:1)

另一个没有itertools的选项:

[[i,j,k] for i in list_1[0] for j in list_1[1] for k in list_1[2]]

如果您按照标题中所述坚持递归:

def product(myList):
    if not myList:
        return [[]]
    else:
        return [[i] + j for i in myList[0] for j in product(myList[1:])]

输出:

[['A', 1, 'X'],
 ['A', 1, 'Y'],
 ['A', 1, 'Z'],
 ['A', 2, 'X'],
 ['A', 2, 'Y'],
 ['A', 2, 'Z'],
 ['A', 3, 'X'],
 ['A', 3, 'Y'],
 ['A', 3, 'Z'],
 ['B', 1, 'X'],
 ['B', 1, 'Y'],
 ['B', 1, 'Z'],
 ['B', 2, 'X'],
 ['B', 2, 'Y'],
 ['B', 2, 'Z'],
 ['B', 3, 'X'],
 ['B', 3, 'Y'],
 ['B', 3, 'Z'],
 ['C', 1, 'X'],
 ['C', 1, 'Y'],
 ['C', 1, 'Z'],
 ['C', 2, 'X'],
 ['C', 2, 'Y'],
 ['C', 2, 'Z'],
 ['C', 3, 'X'],
 ['C', 3, 'Y'],
 ['C', 3, 'Z']]