2012-12-17 29 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]])]