gpt4 book ai didi

python - 多个列表的组合

转载 作者:太空狗 更新时间:2023-10-29 18:19:45 26 4
gpt4 key购买 nike

假设我有三个列表:

list1 --> [a, b, c, d, e, f, g, h]
list2 --> [i, j, k]
list3 --> [l, m, n, o, p]

我希望生成所有组合,其中我从 list1 中获取五个元素,从 list2 中获取两个元素,从 list3 中获取三个元素。

例如。

a, b, c, d, e, i, j, l, m, n  
a, b, c, d, e, i, j, l, m, o
etc.

我尝试使用 itertools.combinations。

l1_combinations = itertools.combinations(list1, 5)
l2_combinations = itertools.combinations(list2, 2)
l3_combinations = itertools.combinations(list3, 3)
for l1_iterator in list(l1_combinations):
for l2_iterator in list(l2_combinations): #added a missing )
for l3_iterator in list(l3_combinations):
sample = l1_iterator + l2_iterator + l3_iterator
print(sample)

但是我得到的输出只有在 list3 上才发生迭代。在所有输出中,仅存在 list1 的前五个元素和 list2 的前两个元素。不存在与这两个列表中其他元素的组合。

有人可以在这里帮助我并解释我到底错过了什么吗?

最佳答案

作为重新生成组合列表的替代方法,预先计算组合的乘积;这也避免了嵌套 for 循环。

from itertools import combinations, product


list1 = list("abcdefgh")
list2 = list("ijk")
list3 = list("lmnop")

l1 = combinations(list1, 5)
l2 = combinations(list2, 2)
l3 = combinations(list3, 3)
for c1, c2, c3 in product(l1, l2, l3):
sample = c1 + c2 + c3
print(sample)

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

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