我遇到了將一個較大的列表拆分爲幾個組合的問題。這裏有一個例子:將列表的子列表拆分爲其他子列表
比方說,我有這樣的名單:
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))])
謝謝
你只需要改變第二個'的append(...)''要延長(...)' – 2012-03-16 03:14:30
感謝gnibbler,這是有幫助! – Akavall 2012-03-16 03:21:29