-1

我需要一些帮助将以下嵌套的 for 循环转换为列表理解。

adj_edges = []
for a in edges:
    adj = []
    for b in edges:
        if b[0] < a[0] and b[1] >= a[0] and b[1] <= a[1]:
            adj.append(b)
    adj_edges.append((a[0], adj))

其中边缘是这样的列表列表 [[0, 200], [200, 400]] 我以前使用过列表推导,但我不知道为什么我遇到了这个问题。

4

1 回答 1

0

这里是:

adj_edges = [(a[0], [b for b in edges if b[0] < a[0] and b[1] >= a[0] and b[1] <= a[1]]) for a in edges]

这是一个交互式会话,展示了两种替代方法:

>>> edges = [[0, 200], [200, 400]]
>>> adj_edges = []
>>> for a in edges:
...     adj = []
...     for b in edges:
...         if b[0] < a[0] and b[1] >= a[0] and b[1] <= a[1]:
...             adj.append(b)
...     adj_edges.append((a[0], adj))
... 
>>> adj_edges
[(0, []), (200, [[0, 200]])]
>>> [(a[0], [b for b in edges if b[0] < a[0] and b[1] >= a[0] and b[1] <= a[1]]) for a in edges]
[(0, []), (200, [[0, 200]])]
于 2012-12-17T21:02:26.437 回答