Python:如何找到n长列表中三个元素的所有可能组合

Python: How to find every possible combination of three elements taken together in n long list

我们有一个列表 [a_1, a_2, a_3,..., a_n] 我们还有一个函数 f(x_1,x_2,x_3)

函数的作用对我的问题并不重要。

在函数参数中,我们需要输入列表中的三个元素。我们需要重复这个过程,直到三个元素的所有可能选择都被函数处理,它们被选择的顺序无关紧要。

4 个元素的示例:

list = [a_1, a_2, a_3, a_4]
result = []
result.append(f(a_1, a_2, a_3))
result.append(f(a_1, a_2, a_4))
result.append(f(a_2, a_3, a_4))
result.append(f(a_4, a_3, a_1))

只是现在我们有 n 个元素。如何自动化查找这些组合的过程。我们不能使用任何花哨的进口产品。我们只能使用 Math 和 Random 导入,不能使用其他。

寻找组合时,itertools 可以完成工作

lst=[i for i in range(1, 5)]

[1, 2, 3, 4]

[i for i in combinations(lst, 3)]
[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]

试试这个:

def comb(m):
    l=m.copy()
    result = []
    while len(l)>3:
        for i in range(1,len(l)-1):
            for k in range(i+1, len(l)):
                result.append(f(l[0], l[i], l[k]))
        l=l[1:]
    result.append(f(l[0], l[1], l[2]))
    return result