[英]Split sublist of a list into other sublists
I am having problems with 'splitting' a larger list into several of it's combinations. 我在将较大的列表“拆分”为多个组合时遇到问题。 Here is an example: 这是一个例子:
Let's say I have this list: 假设我有以下列表:
x = [['a','b'],['c','f'],['q','w','t']]
and I want to end up with 我想结束
x = [['a','b'],['c','f'],['q','w'],['q','t'],['w','t']]
so essentially 所以本质上
['q','w','t']
becomes 变成
['q','w'],['q','t'],['w','t']
I see how I can convert 我知道如何转换
['q','w','t']
to 至
[['q','w'],['q','t'],['w','t']] #notice the extra brackets
with itertools combinations, but then I am stuck with 使用itertools组合,但后来我被困在
x = [['a','b'],['c','f'],[['q','w'],['q','t'],['w','t']]] #notice the extra brackets
Which is not what I want. 这不是我想要的。
How should I do this? 我应该怎么做?
EDIT: 编辑:
Here is the "solution", that does not give me the result that I want: 这是“解决方案”,没有给我想要的结果:
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))])
Thank You 谢谢
I generally use a nested list comprehension to flatten a list like this: 我通常使用嵌套列表理解来扁平化这样的列表:
>>> 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')]
Not the best way to do it but pretty clear for understanding: 这不是最好的方法,但很容易理解:
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']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.