如何将嵌套列表的列表转换为具有唯一数据的列表列表?

How do you convert a list of nested lists into a list of lists with unique data?

在绞尽脑汁创建参考词典和多嵌套查找列表后,我决定必须有一种更简单的方法来完成这项工作。我不可能是第一个进行这种转换的人。我什至不知道从哪里开始在文档中寻找解决方案。

我有一个输出以下数据的系统。

initial_data = [
    [21,[[1],[2,3],[6],[7]]],
    [22,[[4,5],[6,7]],
    [23,[[1],[4,5],[6],[7]]],
    [24,[[1],[2,3,4],[6],[7]]],
]

我有另一个系统需要以下格式的数据(顺序无关紧要)。

return_data = [
    [21,[1,2,6,7]],
    [21,[1,3,6,7]],
    [22,[4,6]],
    [22,[4,7]],
    [22,[5,6]],
    [22,[5,7]],
    [23,[1,4,6,7]],
    [23,[1,5,6,7]],
    [24,[1,2,6,7]],
    [24,[1,3,6,7]],
    [24,[1,4,6,7]],
]

您可以使用 itertools.product,它会产生

Cartesian product of input iterables.

Roughly equivalent to nested for-loops in a generator expression. For example, product(A, B) returns the same as ((x,y) for x in A for y in B).

在每个子列表的第二个元素上使用它应该会产生您需要的结果:

from itertools import product
[[k, p] for k, v in initial_data for p in product(*v)]

# [[21, (1, 2, 6, 7)],
#  [21, (1, 3, 6, 7)],
#  [22, (4, 6)],
#  [22, (4, 7)],
#  [22, (5, 6)],
#  [22, (5, 7)],
#  [23, (1, 4, 6, 7)],
#  [23, (1, 5, 6, 7)],
#  [24, (1, 2, 6, 7)],
#  [24, (1, 3, 6, 7)],
#  [24, (1, 4, 6, 7)]]