転載: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

記事で生成された結果は2次元タプルです。2次元リストに変換する必要がある場合は、記事Pythonカスタム関数を参照して2次元タプルを2次元配列に変換できます。

おすすめ

転載: blog.csdn.net/qq_43511299/article/details/113703577