2012-12-17 30 views
0

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

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] 我用列表解析之前,但我不知道为什么有这个一个麻烦IM 。

回答

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