FreezeJ' Blog

python使用itertools进行排列组合

2023-08-15

itertools 中的排列组合函数,在特定的场景下使用,简洁方便。

from itertools import combinations, permutations

n = int(input("请输入总共的数:"))
nums = list(range(1, n+1))
m = int(input("请输入选取的数字个数:"))

# 组合
combinations_result = list(combinations(nums, m))
print(f"共有{len(combinations_result)}种组合,分别是:{combinations_result}")

# 排列
permutations_result = list(permutations(nums, m))
print(f"共有{len(permutations_result)}种排列,分别是:{permutations_result}")
当n等于4,m等于3的时候:
共有4种组合,分别是:[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
共有24种排列,分别是:[(1, 2, 3), (1, 2, 4), (1, 3, 2), (1, 3, 4), (1, 4, 2), (1, 4, 3), (2, 1, 3), (2, 1, 4), (2, 3, 1), (2, 3, 4), (2, 4, 1), (2, 4, 3), (3, 1, 2), (3, 1, 4), (3, 2, 1), (3, 2, 4), (3, 4, 1), (3, 4, 2), (4, 1, 2), (4, 1, 3), (4, 2, 1), (4, 2, 3), (4, 3, 1), (4, 3, 2)]