为何itertools.product未按预期运行?如何用list_t生成目标列表?
如何用itertools.product从嵌套列表生成目标组合列表
问题背景
首先通过嵌套列表推导式生成嵌套列表list_t:
list_n = [2, 3, 5, 7] list_p = [0, 1, 2, 3] list_t = [[(n, p) for p in list_p] for n in list_n]
生成的list_t结构如下:
list_t = [ [(2, 0), (2, 1), (2, 2), (2, 3)], [(3, 0), (3, 1), (3, 2), (3, 3)], [(5, 0), (5, 1), (5, 2), (5, 3)], [(7, 0), (7, 1), (7, 2), (7, 3)] ]
我们需要生成目标组合列表list_c,要求从list_t的每个子列表中各取一个元素,组合成新的元组,示例结构如下:
list_c = [ [(2, 0), (3, 0), (5, 0), (7, 0)], [(2, 1), (3, 0), (5, 0), (7, 0)], [(2, 2), (3, 0), (5, 0), (7, 0)], [(2, 3), (3, 0), (5, 0), (7, 0)], [(2, 0), (3, 1), (5, 0), (7, 0)], ... ]
但原代码list_c = list(itertools.product(t for t in list_t))无法得到预期结果,它会将list_t中的每个子列表当作单个元素生成元组,输出结果为:
list_c = [ ([(2, 0), (2, 1), (2, 2), (2, 3)],), ([(3, 0), (3, 1), (3, 2), (3, 3)],), ... ]
而手动传入四个子列表itertools.product(list_2, list_3, list_5, list_7)可以得到正确结果。
解决方法
问题核心在于itertools.product的参数要求:它需要接收多个可迭代对象作为位置参数,而非一个包含这些可迭代对象的迭代器。
只需对list_t进行解包操作,用*运算符将list_t中的每个子列表作为独立参数传入product即可:
import itertools list_c = list(itertools.product(*list_t))
此写法与手动传入四个子列表的效果完全一致,会生成所有从每个子列表取一个元素的组合,符合预期的list_c结构。
内容的提问来源于stack exchange,提问作者ssd
相关产品推荐
相关产品推荐

