2012-03-16 152 views
1

我遇到了將一個較大的列表拆分爲幾個組合的問題。這裏有一個例子:將列表的子列表拆分爲其他子列表

比方說,我有這樣的名單:

x = [['a','b'],['c','f'],['q','w','t']] 

,我想用

x = [['a','b'],['c','f'],['q','w'],['q','t'],['w','t']] 

所以落得基本

['q','w','t'] 

成爲

['q','w'],['q','t'],['w','t'] 

我怎麼看,我可以轉換

['q','w','t'] 

[['q','w'],['q','t'],['w','t']] #notice the extra brackets 

與itertools組合,但後來我堅持

x = [['a','b'],['c','f'],[['q','w'],['q','t'],['w','t']]] #notice the extra brackets 

這是不是我想要的。

我該怎麼做?

編輯:

這裏是「解決方案」,即不給我我想要的結果:

from itertools import combinations 

x = [['a','b'],['c','f'],['q','w','t']] 

new_x = [] 

for sublist in x: 
    if len(sublist) == 2: 
     new_x.append(sublist) 
    if len(sublist) > 2: 
     new_x.append([list(ele) for ele in (combinations(sublist,2))]) 

謝謝

+4

你只需要改變第二個'的append(...)''要延長(...)' – 2012-03-16 03:14:30

+0

感謝gnibbler,這是有幫助! – Akavall 2012-03-16 03:21:29

回答

6

我通常使用嵌套列表理解趨於平緩像這樣的一個列表:

>>> x = [['a','b'],['c','f'],['q','w','t']] 
>>> [c for s in x for c in itertools.combinations(s, 2)] 
[('a', 'b'), ('c', 'f'), ('q', 'w'), ('q', 't'), ('w', 't')] 
+0

這就是我想要的!非常感謝你! – Akavall 2012-03-16 03:00:27

2

不是最好的方法,但很明顯的下站立:

from itertools import combinations 

a = [['a','b'],['c','f'],['q','w','t']] 

def get_new_list(x): 

    newList = [] 
    for l in x: 
     if len(l) > 2: 
      newList.extend([list(sl) for sl in combinations(l, 2)]) 
     else: 
      newList.append(l) 
    return newList 

print get_new_list(a) 
>>> [['a','b'],['c','f'],['q','w'],['q','t'],['w','t']]