2016-11-20 16 views
-1

我有一個列表如何將Python中的列表與自己結合?

L=[['g1','g2'],['g3'],['g4','g5','g6']] 

現在我想

L*L=[['g1','g2','g3'],['g1','g2','g4','g5','g6'],['g3','g4','g5','g6']] 

我怎麼做在Python 3.5

+0

你可以在'g5'之後的第一個代碼塊中添加mssing'''嗎?一個字符編輯是不允許的。 – dahrens

回答

3

你想兩件事情

  • itertools.combinations(L, 2)讓所有對列表中的子列表
  • 結合每對做一個新的列表

綜上所述

import itertools 
LL = [a + b for a, b in itertools.combinations(L, 2)] 
+0

itertools沒有工作的人...一些有點名稱錯誤 –

+0

是的,它的工作... thanx人 –

3

嵌套你可以簡單地做這些for循環

l=[[1,2],[3],[4,5,6]] 
lxl=[] 
for i in range(0,len(l)): 
    for j in range(i+1,len(l)): 
     lxl.append(l[i]+l[j]) 

1×會是這個樣子 [[1, 2, 3], [1, 2, 4, 5, 6], [3, 4, 5, 6]]

+0

它的工作... thanx人 –

相關問題