-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))

ここで、edge は [[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]

これは、2 つの代替アプローチを示すインタラクティブなセッションです。

>>> 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 に答える