[英]list of tuples from list of lists Python
Input: List of lists [[1, 2, 3], [5, 6]]
something like that. 输入:列表
[[1, 2, 3], [5, 6]]
东西。
Required Output : list of combinations in tuples [(1), (1, 2), (1, 2, 3), (5), (5, 6)]
. 必需输出 :元组
[(1), (1, 2), (1, 2, 3), (5), (5, 6)]
。
I can imagine how to solve this, but I guess Python has some handy built-in functions for that 我可以想象如何解决这个问题,但我想Python有一些方便的内置函数
AFAIK没有内置函数,但通过列表理解很容易实现这个结果:
[tuple(seq[:i]) for seq in list_of_lists for i in range(1,len(seq)+1)]
If you actually want all combinations of each sublist, you can use itertools
to help: 如果您确实想要每个子列表的所有组合,可以使用
itertools
来帮助:
from itertools import chain, combinations
lst = [[1, 2, 3], [4, 5]]
def powerset(seq, empty=True):
for i in range(0 if empty else 1, len(seq)+1):
for comb in combinations(seq, i):
yield comb
out = list(chain.from_iterable(powerset(l, False) for l in lst))
This gives: 这给出了:
out == [(1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3),
(4,), (5,), (4, 5)]
You could modify this to filter just the tuples matching the start of each sublist, but if that's all you want Bakuriu's solution is more efficient. 您可以修改此选项以仅过滤与每个子列表的开头匹配的元组,但如果这就是您想要的Bakuriu的解决方案更有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.