将列表的子列表拆分为其他子列表

时间:2012-03-16 02:33:57

标签: python list

我遇到了将更大的列表“拆分”成几个组合的问题。这是一个例子:

假设我有这个清单:

  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))])

谢谢

2 个答案:

答案 0 :(得分: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')]

答案 1 :(得分: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']]