三重嵌套列表理解

triple nested list comprehension

我想实现等同于以下循环的列表理解语法

list1 = [1, 2, 3]
list2 = [4, 5, 6]

l = list()
for branch in (list1, list2):
    t = list()
    for block in zip(branch[:-1], branch[1:]):
        t.append(block)
    l.append(t)

但我很难想出相应的理解语法。有人可以帮忙吗?

你可以这样使用列表理解

[list(zip(i, i[1:])) for i in (list1, list2)]

您也可以嵌套列表理解。从字面上翻译你的 for 循环,它将是:

[[block for block in zip(branch[:-1], branch[1:])] for branch in (list1, list2)]

但在这种情况下您可以更好地使用 zip

[list(zip(b, b[1:])) for b in (list1, list2)]