[英]Group consecutive numbers from a list of numbers into a list of tuples using base python (NO itertools or more itertools allowed)
[英]In Python, how can I combine a set of tuples from a list of given tuples without using itertools?
给定如下列表:
[(1, 2), (3, 4, 5), (6,)]
我知道使用 itertools 组合元组列表非常容易。
(1, 3, 6), (1, 4, 6), (1, 5, 6), (2, 3, 6), (2, 4, 6), (2, 5, 6)
但是如何在不使用 itertools 的情况下解决它?
[(x, y, 6) for x in (1, 2) for y in (3, 4, 5)]
另请参阅获取一系列列表的笛卡尔积? 更多通用解决方案
这是一种相当通用的方法,在输入上有一系列循环:
lst = [(1, 2), (3, 4, 5), (6,)]
result = [tuple([l]) for l in lst[0]]
for l in lst[1:]:
out = []
for r in result:
for i in range(len(l)):
out.append((*r, l[i]))
result = out
print(result)
Output:
[(1, 3, 6), (1, 4, 6), (1, 5, 6), (2, 3, 6), (2, 4, 6), (2, 5, 6)]
def product(pools):
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
return result
product([(1,2,3),(4,5),(6,)])
[[1, 4, 6], [1, 5, 6], [2, 4, 6], [2, 5, 6], [3, 4, 6], [3, 5, 6]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.