如何用简洁语法实现list_A取1元素、list_B取2元素的itertools迭代?
用itertools实现扁平化的组合乘积
需求
从list_A中取1个元素,同时从list_B中取2个元素,得到扁平化的元组结果,而非嵌套元组格式。
当前问题
你当前的代码通过itertools.product组合了两个combinations迭代器,但输出结果是嵌套元组(如((1,), ('a', 'b'))),不符合预期的扁平化格式。
解决方案
直接在列表推导式中合并元组,或者用itertools.chain扁平化元素,两种方法都能得到预期结果:
方法1:元组直接相加(最简洁)
import itertools list_A = [1, 2, 3] list_B = ['a', 'b', 'c'] result = [a + b for a, b in itertools.product(itertools.combinations(list_A, 1), itertools.combinations(list_B, 2))] print(result)
输出:
[(1, 'a', 'b'), (1, 'a', 'c'), (1, 'b', 'c'), (2, 'a', 'b'), (2, 'a', 'c'), (2, 'b', 'c'), (3, 'a', 'b'), (3, 'a', 'c'), (3, 'b', 'c')]
原理:itertools.combinations(list_A,1)返回的单元素元组(如(1,))和list_B的双元素元组(如('a','b'))可以直接相加,合并为一个扁平化的元组。
方法2:用itertools.chain扁平化(适合多组元素场景)
如果后续需要组合更多列表的结果,用chain更通用:
import itertools list_A = [1, 2, 3] list_B = ['a', 'b', 'c'] result = [tuple(itertools.chain.from_iterable(item)) for item in itertools.product(itertools.combinations(list_A,1), itertools.combinations(list_B,2))]
原理:chain.from_iterable(item)会把嵌套的元组(如((1,), ('a','b')))展开为单个元素的迭代器,再转成元组即可得到扁平化结果。
内容的提问来源于stack exchange,提问作者johann
相关产品推荐
相关产品推荐

