Python中按位置规则生成多列表元素组合的方法
生成符合位置规则的列表组合
思路梳理
先明确每个位置的候选元素范围:
- 第1位:
x[0]、y[0]、z[0]→["a", "d", "m"] - 第2位:
x[1]、y[1]、z[1]→["b", "e", "n"] - 第3位:
x[2]、y[2]、z[2]→["c", "f", "s"]
利用itertools.product可以高效生成这三个候选集合的笛卡尔积,直接得到所有符合要求的3元素组合,比嵌套for循环简洁得多。
代码实现
方式一:手动整理候选元素
import itertools x = ["a", "b", "c"] y = ["d", "e", "f"] z = ["m", "n", "s"] # 定义每个位置的候选元素集合 pos1 = [x[0], y[0], z[0]] pos2 = [x[1], y[1], z[1]] pos3 = [x[2], y[2], z[2]] # 生成所有组合(结果为元组列表) all_combinations = list(itertools.product(pos1, pos2, pos3)) # 如需转换为列表形式 all_combinations_as_lists = list(map(list, all_combinations)) # 输出示例 for combo in all_combinations: print(combo)
方式二:用zip简化候选元素整理
利用zip快速提取三个列表的对应位置元素,再解包传给itertools.product,代码更简洁:
import itertools x = ["a", "b", "c"] y = ["d", "e", "f"] z = ["m", "n", "s"] # zip(x,y,z)生成三个元组:('a','d','m'), ('b','e','n'), ('c','f','s') # *解包后作为product的参数,直接生成所有组合 all_combinations = list(itertools.product(*zip(x, y, z))) print(all_combinations)
输出结果
两种方式都会生成总计27种符合规则的组合,示例片段如下:
('a', 'b', 'c'), ('a', 'b', 'f'), ('a', 'b', 's'), ('a', 'e', 'c'), ('a', 'e', 'f'), ('a', 'e', 's'), ...(剩余组合省略)
内容的提问来源于stack exchange,提问作者Steve
相关产品推荐
相关产品推荐

