python - 1,2,3,4组成无重复的三位数有多少种组合

方法一:

三个循环

def not_repeat(params):
    # 定义一个空列表
    mlist = []
    count = 0
    for i in params:
        for j in params:
            for m in params:
                # 三个数不相等
                if i != j and j != m and i != m:
                    mlist.append(i+j+m)  # params 为字符串,字符串拼接
                    count += 1
    print("一共有 {} 种组合,分别是 {}" .format(count, mlist))


not_repeat('1234')


方法二:


'''
使用 python 全排列 permutations 函数

itertools.permutations(iterable, r=None)
连续返回由 iterable 元素生成长度为 r 的排列。

'''
from itertools import permutations
# 打印每种组合情况
for i, j, m in permutations([1, 2, 3, 4], 3):
    print(i, j, m)

# len 函数统计总数
count = len(list(permutations([1, 2, 3, 4], 3)))
print(count)

posted @ 2022-12-03 16:48  西瓜_皮  阅读(645)  评论(0编辑  收藏  举报