2017-02-25 36 views
-2
的列表中的項目可能的組合

假設我有一個嵌套列表看起來像這樣:的Python:在列表

nested_list = [[a,b,1],[c,d,3],[a,f,8],[a,c,5]] 

現在我想要得到的列表的第二項之間的所有可能的組合,但只如果兩個列表中的第一項都相等。那麼應該怎麼打印如下:

Combinations for 'a' as first item in the lists: [b,f], [b,c], [f,c] 

我想出了這一點:

comprehension = [x[0] for x in nested_list if x[1] in nested_list] 

但這不起作用(ofcourse)。我不知道如何遍歷所有列表才能找到組合。

+0

看起來你要我們寫一些代碼給你。儘管許多用戶願意爲遇險的編碼人員編寫代碼,但他們通常只在海報已嘗試自行解決問題時才提供幫助。展示這一努力的一個好方法是包含迄今爲止編寫的代碼,示例輸入(如果有的話),期望的輸出以及實際獲得的輸出(輸出,回溯等)。您提供的細節越多,您可能會收到的答案就越多。檢查[FAQ](http://stackoverflow.com/tour)和[如何提問](http://stackoverflow.com/questions/how-to-ask)。 – TigerhawkT3

回答

0

您可以使用collectoins.defaultdictcombinations

In [2]: nested_list = [['a','b',1],['c','d',3],['a','f',8],['a','c',5]] 

In [3]: from collections import defaultdict 

In [4]: from itertools import combinations 

In [5]: d = defaultdict(list)  

In [6]: for i, j, _ in nested_list: 
    ...:  d[i].append(j) 
    ...:  

In [7]: {k: list(combinations(v, 2)) for k, v in d.items()} 
Out[7]: {'a': [('b', 'f'), ('b', 'c'), ('f', 'c')], 'c': []}