首页 > 解决方案 > 打印所有两位数字组合且某些数字不重复的程序

问题描述

有人可以告诉我如何创建一个快速的 python 程序来打印所有可能的两位数字组合:1、2 和 3。没有重复,所以没有 11、22 或 33。

标签: python

解决方案


您可以将列表理解与条件一起使用(以排除相同的数字情况)。

digits = [1, 2, 3]
output = [(x, y) for x in digits for y in digits if x != y]
print(output)
# [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]

一种更通用、更方便的方法(由 Chris 建议)是使用itertools.permutation

import itertools
output = list(itertools.permutations([1, 2, 3], 2))

推荐阅读