gpt4 book ai didi

python - python中列表组合的问题

转载 作者:行者123 更新时间:2023-11-28 22:14:41 26 4
gpt4 key购买 nike

我有一些 Python 列表,其中包含我想要连接的信息。这些列表类似于这些:

vars1 = ["x1", "x2"]
vars2 = ["y1", "y2"]
main_list = ["a","b","c","d"]

我想要的是获得所有可能的组合(即使我不知道正确的操作名称)以涵盖我在下面列出的所有情况:

[
("x1,a,x2", "y1,a,y2"), ("x1,a,x2", "y1,b,y2"),
("x1,a,x2", "y1,c,y2"), ("x1,a,x2", "y1,d,y2"),
("x1,b,x2", "y1,a,y2"), ("x1,b,x2", "y1,b,y2"),
("x1,b,x2", "y1,c,y2"), ("x1,b,x2", "y1,d,y2")
("x1,c,x2", "y1,a,y2"), ("x1,c,x2", "y1,b,y2"),
("x1,c,x2", "y1,c,y2"), ("x1,c,x2", "y1,d,y2"),
("x1,d,x2", "y1,a,y2"), ("x1,d,x2", "y1,b,y2"),
("x1,d,x2", "y1,c,y2"), ("x1,d,x2", "y1,d,y2"),
]

我调查了 itertools.product 函数,但我得不到想要的结果。

如果你能帮助我,我将不胜感激。

最佳答案

你的问题不是很清楚,但这看起来像你想要的(如果我错了请纠正我):

vars1 = ["x1", "x2"]
vars2 = ["y1", "y2"]
main_list = ["a","b","c","d"]
result = []

for a1, a2 in itertools.product(main_list, main_list):
result.append((','.join((vars1[0], a1, vars1[1])), ','.join((vars2[0], a2, vars2[1]))))

换句话说,形式为 ('x1,<a1>,x2', 'y1,<a2>,y2') 的值对于所有 (<a1>, <a2>)在集合的笛卡尔积中 {'a', 'b', 'c', 'd'}与自己,这确实是itertools.product是为了。

结果:

[('x1,a,x2', 'y1,a,y2'),
('x1,a,x2', 'y1,b,y2'),
('x1,a,x2', 'y1,c,y2'),
('x1,a,x2', 'y1,d,y2'),
('x1,b,x2', 'y1,a,y2'),
('x1,b,x2', 'y1,b,y2'),
('x1,b,x2', 'y1,c,y2'),
('x1,b,x2', 'y1,d,y2'),
('x1,c,x2', 'y1,a,y2'),
('x1,c,x2', 'y1,b,y2'),
('x1,c,x2', 'y1,c,y2'),
('x1,c,x2', 'y1,d,y2'),
('x1,d,x2', 'y1,a,y2'),
('x1,d,x2', 'y1,b,y2'),
('x1,d,x2', 'y1,c,y2'),
('x1,d,x2', 'y1,d,y2')]

关于python - python中列表组合的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53329521/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com