将for循环转换为list comprehension python

时间:2012-12-17 20:37:58

标签: list for-loop list-comprehension nested-loops

我需要一些帮助将以下嵌套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]]这样的列表列表 我之前使用过列表推导但我不知道为什么我遇到这个问题。

1 个答案:

答案 0 :(得分: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]])]