转载:Python列表的排列组合

原文链接:python实现列表的排列组合

可重复组合:

from itertools import product
import numpy
def test_func11(num_list,lengths):
    num=len(num_list)
    res_list=list(product(num_list,repeat=lengths))
    print(res_list)
    print('元素可以重复出现排列总数为:', len(res_list))
a=[1,2,3,4,5]
aLength=len(a)
test_func11(a,aLength)

结果:

[(1, 1, 1, 1, 1), (1, 1, 1, 1, 2), (1, 1, 1, 1, 3), (1, 1, 1, 1, 4), ...]
元素可以重复出现排列总数为: 3125

不重复组合:

from itertools import product,permutations
def test_func12(num_list):
    tmp_list = permutations(num_list)
    res_list=[]
    for one in tmp_list:
        res_list.append(one)
    print(res_list)
    print('元素不允许重复出现排列总数为:', len(res_list))
a=[1,2,3,4,5]
aLength=len(a)
test_func12(a)

结果:

[(1, 2, 3, 4, 5), (1, 2, 3, 5, 4), (1, 2, 4, 3, 5), ...]
元素不允许重复出现排列总数为: 120

文中生成结果为二维元组,如果需要转换成二维列表,可以参考文章Python二维元组转换成二维数组的自定义函数

猜你喜欢

转载自blog.csdn.net/qq_43511299/article/details/113703577