Skip to main content
 首页 » 编程设计

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

2025年05月04日14langtianya

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

假设我有这个列表:

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

谢谢

请您参考如下方法:

我通常使用嵌套列表理解来展平这样的列表:

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